【发布时间】:2016-05-15 14:25:37
【问题描述】:
我正在使用 tcpclient 数组,我已将不同的设备设置为 tcp 服务器,我的 c# Gui 充当所有设备的客户端。我知道网络中每个设备的每个地址 ip,这样我就可以毫无问题地设置每个 tcp 客户端。好吧,现在我希望 GUI 可以识别所有服务器,而无需我手动设置 IP 地址。我该怎么做? 起初我想获取 pc 的本地 IP 地址,以便获得基本网络(完成),然后我想声明一个 tcpclient 数组,它试图连接到所有可能的 IP 地址,但这需要很多时间。
public void GetLocalIPAddress() // get the local ip of the pc
{
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName()).Where(address => address.AddressFamily == AddressFamily.InterNetwork).First();
textBox2.Text = ip.ToString();
string aux = ip.ToString();
int num = aux.IndexOf(".");
byte0 = aux.Substring(0,num);
aux = aux.Substring(num + 1);
num = aux.IndexOf(".");
byte1 = aux.Substring(0, num);
aux = aux.Substring(num + 1);
num = aux.IndexOf(".");
byte2 = aux.Substring(0, num);
aux = aux.Substring(num + 1);
// if ip Address = 192.168.1.156 ==> byte0 =192 / byte1=168/ byte2=1
}
private void GetConnectedSensoren()
{
for (int k = 2; k < 254; k++ ) // intialize the tab with all the possible ip Addresses
{
myhostName[k] = byte0 + "." + byte1 + "." + byte2 + "."+k;
try
{
myclient[k] = new TcpClient(myhostName[k], portNum);
}
catch
{
MessageBox.Show("executed here");
}
}
}
【问题讨论】: