简体   繁体   English

c#TCPclient设置IP

[英]c# TCPclient set IP

I'm trying to send a packet using httpclient 我正在尝试使用httpclient发送数据包

TcpClient tc = new TcpClient(ip, 4500);

            string s = "A7007000601D3B00";

            byte[] arr = new byte[s.Length/2];
            for ( var i = 0 ; i<arr.Length ; i++ ){
             arr[i] = (byte)Convert.ToInt32(s.Substring(i*2,2), 16);
            }

            NetworkStream stream = tc.GetStream();
            stream.Write(arr, 0, arr.Length);
            tc.Close();

The problem is that it sends from port 47109, however i need to send the packet using port 46324. How do i set this? 问题是它从端口47109发送,但是我需要使用端口46324发送数据包。我如何设置它?

There is an overload of the TcpClient constructor that allows you to bind it to a specific local IP address and port. TcpClient构造函数存在重载,允许您将其绑定到特定的本地IP地址和端口。 See the documentation on MSDN . 请参阅MSDN上的文档

The reason the example at Is there a way to specify the local port to used in tcpClient? 这个例子的原因是否有办法指定tcpClient中使用的本地端口? is not working is probably because the first address on the list is not actually the local machine ip address. 不工作可能是因为列表中的第一个地址实际上不是本地机器的ip地址。 Something like this might fix the issue and pull the proper local IP address: 这样的事情可能会解决问题并提取适当的本地IP地址:

string remoteIP = "x.x.x.x";
IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).First();
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 47109);
TcpClient clientSocket = new TcpClient(ipLocalEndPoint);
clientSocket.Connect(remoteIP, 4500);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM