Ale*_*exT 0 java sockets networking ip-address inetaddress
我正在尝试编写一个简单的程序客户端服务器程序,该程序将客户端计算机连接到服务器计算机。
到目前为止,我的代码在localhost上运行良好,但是当我将客户端代码中的IP地址替换为服务器计算机的本地IP地址时,则未完成连接。我认为我的理解InetAddress不对。
套接字连接代码:Client.java
InetAddress ip = InetAddress.getByName("my_ip_address");
Socket s = new Socket(ip, 9876); //<- where the connection timeout happens
Run Code Online (Sandbox Code Playgroud)
您不会getBytes()从a 拨打电话String那样获得您的IP地址;选项1:致电getByName(String)喜欢
InetAddress ip = InetAddress.getByName("127.0.0.1");
Run Code Online (Sandbox Code Playgroud)
选择2:构造适当的byte[]。喜欢,
InetAddress ip = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
Run Code Online (Sandbox Code Playgroud)