获取本机IP
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Net.NetworkInformation; namespace netWindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //以下测试状况,电脑绑定了两个有线网ip,不通外网,和两个虚拟机ip private void get_ip_button_Click(object sender, EventArgs e) { //获取本机ip方法1 IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { //判断是否是ipv4地址,如果判断ipv6地址用InterNetworkV6 if (ip.AddressFamily == AddressFamily.InterNetwork) listBox1.Items.Add(ip.ToString()); } //获取本机ip方法1 string localIP = string.Empty; using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0)) { socket.Connect("8.8.8.8", 65530); IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint; localIP = endPoint.Address.ToString(); } listBox2.Items.Add(localIP); //获取本机ip方法3 getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Ethernet); } //获取本机ip方法3 public void getLocalIPAddressWithNetworkInterface(NetworkInterfaceType _type) { foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) { if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up) { foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { listBox3.Items.Add(ip.Address.ToString()); } } } } } private void start_button_Click(object sender, EventArgs e) { //Socket sever = new Socket(AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp ); //if() } } }
电脑绑定了两个ip和两个虚拟机ip
结果