//创建连接的Socket
Socket client;
try
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
String HostName = Dns.GetHostName(); // 获得计算机的名字
listBox1.Items.Add("本机名称: "+HostName);//显示计算机名字
IPHostEntry iPHostEntry = Dns.GetHostEntry(HostName);//获取地址
var addressV = iPHostEntry.AddressList.FirstOrDefault(q => q.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);//ipv4地址
if (addressV != null)
{
if (addressV.IsIPv6LinkLocal == true)//判断是否使用IPV6 寻址
{
//
}
else
{
listBox1.Items.Add("本机IP类型为IPV4 ");
listBox1.Items.Add("本机IP: " + addressV.ToString());
}
}
else
listBox1.Items.Add("本机IP: " + "ERROR");
}
catch (Exception ex)
{
MessageBox.Show("接收服务端发送的消息出错:" + ex.ToString());
}
//方法2 推荐
String Str_IP = "6";
System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
for (int i = 0; i < addressList.Length; i++)
{
Str_IP = addressList[i].ToString();
}
listBox1.Items.Add("本机IP: " + Str_IP);