개발팁2022. 4. 7. 11:53

PC에 이더넷 어댑터가 여러개 설치되어 있거나, Virtual Box 와 같은 Virtual Marchine 이 설치되어 있다면,

IP주소 / 맥어드레스를 구하는 다른 소스로는 엉뚱한 IP/Mac 주소를 반환하는 경우가 있다.

정확한 사용 주소를 가져오는 C# 코드는 아래와 같다.

 

 

IP주소

 

            string ipAddress = "";

            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
            {
                socket.Connect("8.8.8.8", 65530);
                IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
                ipAddress = endPoint.Address.ToString();
            }

 

 

맥어드레스

 

            string macAddress = "";

            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            using (ManagementObjectCollection moc = mc.GetInstances())
            {
                foreach (ManagementObject mo in moc)
                {
                    if (mo["MacAddress"] != null)
                    {
                        if ((bool)mo["IPEnabled"] == true)
                        {
                            macAddress = mo["MacAddress"].ToString();
                            break;
                        }

                        mo.Dispose();
                    }
                }

            }
Posted by 헝개