【问题标题】:how to get know the client port and ip address in client socket program in java [closed]如何在java中的客户端套接字程序中知道客户端端口和IP地址[关闭]
【发布时间】:2012-12-02 07:32:33
【问题描述】:

我使用套接字在 java 中创建了多个客户端-服务器通信。我有一个服务器和一个客户端。我想用多个客户端测试我的程序。我计划创建一个动态创建 ip 和端口的模拟器。为此我只想知道如何在套接字程序中设置客户端 ip 和端口。任何人都可以帮助我.. 我使用 InetAddress.getByName 来获取客户端地址。

 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");
     }
}

【问题讨论】:

  • 这段代码似乎来自 java.net.Socket。与您的问题的联系使我无法理解。你的问题本身让我无法理解。

标签: java sockets network-programming client-server


【解决方案1】:

试试这个

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

【讨论】:

    【解决方案2】:

    简单。要创建客户端 IP 和端口,您应该在主程序中传递如下参数。

    就这样试试

               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);
                    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      相关资源
      最近更新 更多