模拟多个具有不同IP的客户端连接到服务器套接字

huangapple go评论61阅读模式
英文:

Simulate Multiple clients with different IPs to server socket

问题

我有一个服务器套接字应用程序,可以接受多个客户端。我想用Java编写客户端应用程序,向服务器应用程序发送请求。是否有办法模拟具有不同IP的多个客户端连接到服务器应用程序?

谢谢,
Vinodhini。

英文:

I have a server socket application which accepts multiple client. I want to write client application in java which send request to server application. Is there any way I can simulate multiple clients with different IPs to the server application

Thanks,
Vinodhini.

答案1

得分: 1

请检查以下方法是否对您有帮助?

我已经在同一台Linux机器上验证了这个解决方案。

我的Linux机器只有一张网卡(网络接口卡)。

临时添加了多个IP地址到这个网卡上。

您可以使用'ifconfig'命令向网卡添加IP地址。但请注意,这个IP地址在重新启动机器后将不可用。在这里,我们假设您已经有一个配置了静态IP的网卡。如果我们需要向此接口添加两个额外的IP地址,比如192.168.1.25和192.168.1.26,我们可以通过以root用户身份执行以下命令来实现:

ifconfig eth0:1 192.168.1.25 netmask 255.255.255.0
ifconfig eth0:2 192.168.1.26 netmask 255.255.255.0

添加后:

/sbin/ifconfig

eth0      Link encap:Ethernet  HWaddr xx:xx:xx:xx:xx:xx
          inet addr:10.x.x.x  Bcast:x.x.x.x  Mask:255.255.x.xx

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.x.x.x
		  
eth0:1    Link encap:Ethernet  HWaddr xx:xx:xx:xx:xx:xx
          inet addr:192.168.1.25  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

eth0:2    Link encap:Ethernet  HWaddr xx:xx:xx:xx:xx:xx
          inet addr:192.168.1.27  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

现在,我的Linux主机有两个额外的临时IP地址。

我在我的Linux机器上运行以下服务器套接字程序。

RemoteFileServer.java

// 代码省略

执行:

java -cp .  socket/learning/RemoteFileServer 9999

我在我的Linux机器上运行以下客户端套接字程序。

为了将客户端套接字绑定到本地地址,使用以下Socket构造函数

// 代码省略

RemoteFileClient.java

// 代码省略

执行:

java -cp .  socket/learning/RemoteFileClient 10.x.x.x 9999 /tmp/test.log 192.168.1.27
java -cp .  socket/learning/RemoteFileClient 10.x.x.x 9999 /tmp/test.log 192.168.1.25
java -cp .  socket/learning/RemoteFileClient 10.x.x.x 9999 /tmp/test.log 10.x.x.x
java -cp .  socket/learning/RemoteFileClient 10.x.x.x 9999 /tmp/test.log 127.0.0.1

相应的服务器控制台输出:

Client socket details:  getInetAddress  /192.168.1.27    getLocalAddress  /10.x.x.x   getRemoteSocketAddress  /192.168.1.27:14774
Client socket details:  getInetAddress  /192.168.1.25    getLocalAddress  /10.x.x.x   getRemoteSocketAddress  /192.168.1.25:29188
Client socket details:  getInetAddress  /10.x.x.x    getLocalAddress  /10.x.x.x   getRemoteSocketAddress  /10.x.x.x:42407
Client socket details:  getInetAddress  /127.0.0.1    getLocalAddress  /10.x.x.x   getRemoteSocketAddress  /127.0.0.1:36002
英文:

Please check if following approach help you?

I have verified the solution on Linux within same machine.

my Linux machine have only one NIC(Network Interface Card).

/sbin/ifconfig

eth0      Link encap:Ethernet  HWaddr xx:xx:xx:xx:xx:xx
          inet addr:10.x.x.x  Bcast:x.x.x.x  Mask:255.255.x.xx

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.x.x.x

I have temporarily added multiple IP addresses to this NIC

You can use the 'ifconfig' command to add an IP address to a NIC. But, please note that this IP address will not be available after rebooting the machine. Here, we assume that you already have a NIC with a static IP configured in it. If we need to add two more IP addresses, say 192.168.1.25 and 192.168.1.26 to this interface, we can accomplish this by executing the following commands as root user:

ifconfig eth0:1 192.168.1.25 netmask 255.255.255.0
ifconfig eth0:2 192.168.1.26 netmask 255.255.255.0

Post addition:

/sbin/ifconfig

eth0      Link encap:Ethernet  HWaddr xx:xx:xx:xx:xx:xx
          inet addr:10.x.x.x  Bcast:x.x.x.x  Mask:255.255.x.xx

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.x.x.x
		  
eth0:1    Link encap:Ethernet  HWaddr xx:xx:xx:xx:xx:xx
          inet addr:192.168.1.25  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

eth0:2    Link encap:Ethernet  HWaddr xx:xx:xx:xx:xx:xx
          inet addr:192.168.1.27  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

Now my Linux host has 2 extra temporary IP Address.

I am running following Server Socket program on my Linux machine

RemoteFileServer.java

package socket.learning;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;

public class RemoteFileServer {
	public static void main(String[] args) {
		RemoteFileServer server = new RemoteFileServer();
		server.acceptConnections(Integer.parseInt(args[0]));
	}

	public void acceptConnections(int listenPort) {
		try {
			ServerSocket server = new ServerSocket(listenPort);
			Socket incomingConnection = null;
			while (true) {
				incomingConnection = server.accept();
				handleConnection(incomingConnection);
			}
		} catch (BindException e) {
			System.out.println("Unable to bind to port " + listenPort);
		} catch (IOException e) {
			System.out.println("Unable to instantiate a ServerSocket on port: "
					+ listenPort);
		}
	}

	public void handleConnection(Socket incomingConnection) {
		try {
			System.out.println("Client socket details:  getInetAddress  "
					+ incomingConnection.getInetAddress()
					+ "    getLocalAddress  "
					+ incomingConnection.getLocalAddress()
					+ "   getRemoteSocketAddress  "
					+ incomingConnection.getRemoteSocketAddress());
			OutputStream outputToSocket = incomingConnection.getOutputStream();

			InputStream inputFromSocket = incomingConnection.getInputStream();
			BufferedReader streamReader = new BufferedReader(
					new InputStreamReader(inputFromSocket));
			String fileName = streamReader.readLine();
			FileReader fileReader = new FileReader(new File(fileName));
			BufferedReader bufferedFileReader = new BufferedReader(fileReader);
			PrintWriter streamWriter = new PrintWriter(outputToSocket);
			String line = null;
			while ((line = bufferedFileReader.readLine()) != null) {
				streamWriter.println(line);
			}
			fileReader.close();
			streamWriter.close();
			streamReader.close();
		} catch (Exception e) {
			System.out.println("Error handling a client: " + e);
		}
	}
}

Execution:

java -cp .  socket/learning/RemoteFileServer 9999

9999 is Server socket bind/listen port.

Running following Client Socket program on my Linux machine

To bind client socket to a local address using following Socket constructor

public Socket(InetAddress address,
      int port,
      InetAddress localAddr,
      int localPort)
       throws IOException
Creates a socket and connects it to the specified remote address on the specified remote port. The Socket will also bind() to the local address and port supplied.
If the specified local address is null it is the equivalent of specifying the address as the AnyLocal address (see InetAddress.isAnyLocalAddress()).

A local port number of zero will let the system pick up a free port in the bind operation.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Parameters:
address - the remote address
port - the remote port
localAddr - the local address the socket is bound to, or null for the anyLocal address.
localPort - the local port the socket is bound to or zero for a system selected free port.

RemoteFileClient.java

package socket.learning;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class RemoteFileClient {
	protected String hostIP;
	protected int hostPort;
	protected BufferedReader socketReader;
	protected PrintWriter socketWriter;

	public RemoteFileClient(String hostIP, int hostPort) {
		this.hostIP = hostIP;
		this.hostPort = hostPort;
	}

	public static void main(String[] args) {
		RemoteFileClient remoteFileClient = new RemoteFileClient(args[0],
				Integer.parseInt(args[1]));
		remoteFileClient.setUpConnection(args[3]);
		String fileContents = remoteFileClient.getFile(args[2]);
		remoteFileClient.tearDownConnection();
		System.out.println(fileContents);
	}

	public void setUpConnection(String clientIpAddress) {
		try {
			Socket client = new Socket(hostIP, hostPort,
					InetAddress.getByName(clientIpAddress), 0);
			socketReader = new BufferedReader(new InputStreamReader(
					client.getInputStream()));
			socketWriter = new PrintWriter(client.getOutputStream());
		} catch (UnknownHostException e) {
			System.out
			.println("Error setting up socket connection: unknown host at "
					+ hostIP);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Error setting up socket connection: " + e);
		}
	}

	public String getFile(String fileNameToGet) {
		StringBuffer fileLines = new StringBuffer();
		try {
			socketWriter.println(fileNameToGet);
			socketWriter.flush();
			String line = null;
			while ((line = socketReader.readLine()) != null)
				fileLines.append(line + "\n");
		} catch (IOException e) {
			System.out.println("Error reading from file: " + fileNameToGet);
		}
		return fileLines.toString();
	}

	public void tearDownConnection() {
		try {
			socketWriter.close();
			socketReader.close();
		} catch (IOException e) {
			System.out.println("Error tearing down socket connection: " + e);
		}
	}
}

Execution:

java -cp .  socket/learning/RemoteFileClient 10.x.x.x 9999 /tmp/test.log 192.168.1.27
java -cp .  socket/learning/RemoteFileClient 10.x.x.x 9999 /tmp/test.log 192.168.1.25
java -cp .  socket/learning/RemoteFileClient 10.x.x.x 9999 /tmp/test.log 10.x.x.x
java -cp .  socket/learning/RemoteFileClient 10.x.x.x 9999 /tmp/test.log 127.0.0.1

Corresponding Server console output:

Client socket details:  getInetAddress  /192.168.1.27    getLocalAddress  /10.x.x.x   getRemoteSocketAddress  /192.168.1.27:14774
Client socket details:  getInetAddress  /192.168.1.25    getLocalAddress  /10.x.x.x   getRemoteSocketAddress  /192.168.1.25:29188
Client socket details:  getInetAddress  /10.x.x.x    getLocalAddress  /10.x.x.x   getRemoteSocketAddress  /10.x.x.x:42407
Client socket details:  getInetAddress  /127.0.0.1    getLocalAddress  /10.x.x.x   getRemoteSocketAddress  /127.0.0.1:36002

huangapple
  • 本文由 发表于 2020年9月25日 16:23:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64060492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定