how to get know the client port and ip address in client socket program in java [closed]

耗尽温柔 提交于 2019-12-20 07:26:33

问题


I created a multiple client- server communication in java using socket. i have a single server and a client. i want to test my program with multiple clients. i m planning to create a simulator which dynamically create ip and port.. for that i just want to know how to set the client ip and port in the socket program. can anyone help me.. i use InetAddress.getByName to get the client address.

 public Socket(Proxy proxy)
  {
     if (proxy != null && proxy.type() == Proxy.Type.SOCKS) 
   { 
    SecurityManager security = System.getSecurityManager();
         InetSocketAddress epoint = (InetSocketAddress) proxy.address();
         if (security != null) {
             if (epoint.isUnresolved())
                epoint = new InetSocketAddress(epoint.getHostName(), epoint.getPort());
            if (epoint.isUnresolved())
                security.checkConnect(epoint.getHostName(),
                                      epoint.getPort());
            else
                security.checkConnect(epoint.getAddress().getHostAddress(),
                                      epoint.getPort());
        }
         impl = new SocksSocketImpl(proxy);
        impl.setSocket(this);
    } else {
        if (proxy == Proxy.NO_PROXY) {
            if (factory == null) {
                impl = new PlainSocketImpl();
                impl.setSocket(this);
             } else
                setImpl();
        } else
            throw new IllegalArgumentException("Invalid Proxy");
     }
}

回答1:


Try this for

clientString = "Remote client: " + socket.getRemoteSocketAddress().toString().substring(1);



回答2:


Simple. To create the client IP and port you should pass the parameters like below in main program.

just try like this

           java Client localhost 1112 //To run

           (ip: localhost
           port: 1112)

            // Code for main

                 public static void main(String[] args)

            {

          try

             {

                    ipAdd=args[0];

                    portNo=Integer.parseInt(args[1]);

                    Client s=new Client();  

             }

           catch (Exception e)

                {

                        System.out.println(e);
                }

}


来源:https://stackoverflow.com/questions/13876303/how-to-get-know-the-client-port-and-ip-address-in-client-socket-program-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!