[英]how to Display IPv4 Address Not IPv6
I am having this problem, I wrote a small app to display the computers hostname and IP address. 我遇到这个问题,我写了一个小应用程序来显示计算机的主机名和IP地址。
Hostname horks no problem, the issue I am sitting with is... 主机名没问题,我坐的问题是......
On some Windows 7 / 8 computers is displays the IPv6 Frown | 在某些Windows 7/8计算机上显示IPv6 Frown | :(
:(
How do I force to only return IPv4 everytime? 我如何强制每次只返回IPv4?
This is my Code: 这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace IPChecker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "Host Computer: " + Dns.GetHostName();
foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))
{
label2.Text = "IP Address: " + address;
}
}
}
}
Try this.. 尝试这个..
Declare a String.. 声明一个字符串..
public static string Ipv4()
{
string ipv4Address = String.Empty;
foreach (IPAddress currentIPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (currentIPAddress.AddressFamily.ToString() == System.Net.Sockets.AddressFamily.InterNetwork.ToString())
{
ipv4Address = currentIPAddress.ToString();
break;
}
}
return ipv4Address;
}
Have you tried with an empty hostname ? 你试过空主机名吗?
Following MSDN ( http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses(v=vs.110).aspx ) : 以下MSDN( http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses ( v=vs.110 ) .aspx ):
When an empty string is passed as the host name, this method returns the IPv4 addresses of the local host for all operating systems except Windows Server 2003;
当空字符串作为主机名传递时,此方法返回除Windows Server 2003以外的所有操作系统的本地主机的IPv4地址。 for Windows Server 2003, both IPv4 and IPv6 addresses for the local host are returned.
对于Windows Server 2003,将返回本地主机的IPv4和IPv6地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.