2013-03-18 75 views
0

我試圖用發送一個數據包的HttpClientC#TcpClient的集IP

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

的問題是,它從端口47109發送,不過,我需要使用端口46324.發送數據包如何設置這個?

+1

可能的重複。看看http://stackoverflow.com/questions/2869840/is-there-a-way-to-specify-the-local-port-to-used-in-tcpclient – coolmine 2013-03-18 16:44:22

+0

它不工作,得到一個clientSocket.Connect上的錯誤(remoteHost,remotePort); – 2013-03-18 16:49:07

+0

答案解釋了爲什麼,雖然你沒有說錯誤是什麼,我認爲這可能是問題所在。 – coolmine 2013-03-18 17:01:40

回答

1

Is there a way to specify the local port to used in tcpClient?上的示例不起作用的原因可能是因爲列表中的第一個地址實際上並不是本地計算機的ip地址。像這樣的東西可能會解決問題並拉出正確的本地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);