How to Change Public IP Address in C#

2019-06-13 17:35发布

I am creating a C# winform application, in which I want to change the Public IP Address, NOT the IPv4 Address like (Hotspot-Shield, ZenMate, OpenVPN, and others do).

I have checked the following links but didn't find enough help, so I am posting this question:

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

Changing IP address in C#

I write the same code as in the answer of 1st link and also used the libraries but when I check my IP address through google.com it remains the same. I don't know the socket programming.

Here is my code:

namespace WindowsFormsApplication1
{
class ChangeIP
{
    public void SetIP(string ipAddress, string subnetMask, string gateway)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(managementObject => (bool)managementObject["IPEnabled"]))
                {
                    using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
                    {
                        // Set new IP address and subnet if needed
                        if ((!String.IsNullOrEmpty(ipAddress)) || (!String.IsNullOrEmpty(subnetMask)))
                        {
                            if (!String.IsNullOrEmpty(ipAddress))
                            {
                                newIP["IPAddress"] = new[] { ipAddress };
                            }

                            if (!String.IsNullOrEmpty(subnetMask))
                            {
                                newIP["SubnetMask"] = new[] { subnetMask };
                            }

                            managementObject.InvokeMethod("EnableStatic", newIP, null);
                        }

                        // Set mew gateway if needed
                        if (!String.IsNullOrEmpty(gateway))
                        {
                            using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
                            {
                                newGateway["DefaultIPGateway"] = new[] { gateway };
                                newGateway["GatewayCostMetric"] = new[] { 1 };
                                managementObject.InvokeMethod("SetGateways", newGateway, null);
                            }
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// Set's the DNS Server of the local machine
    /// </summary>
    /// <param name="nic">NIC address</param>
    /// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
    /// <remarks>Requires a reference to the System.Management namespace</remarks>
    public void SetNameservers(string nic, string dnsServers)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(objMO => (bool)objMO["IPEnabled"] && objMO["Caption"].Equals(nic)))
                {
                    using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
                    {
                        newDNS["DNSServerSearchOrder"] = dnsServers.Split(',');
                        managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                    }
                }
            }
        }
    }
}
}

And Here is how I am calling those methods:

{
static string local_ip;
string public_ip;

public static string GetLocalIPAddress()  //Method For Getting Local Machine IP
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        throw new Exception("Local IP Address Not Found!");
    }
// Mehod End
            local_ip = GetLocalIPAddress();
            ChangeIP ip = new ChangeIP();
            ip.SetIP(local_ip, null, null); // Calling Method
            var getNIC = NetworkInterface.GetAllNetworkInterfaces();
            NetworkInterface[] NI = NetworkInterface.GetAllNetworkInterfaces();
            string nic = string.Empty;
            string dnsServer = string.Empty;
            foreach(var r in getNIC)
            {
                nic = r.Name;                    
            }
            foreach(NetworkInterface ninter in NI)
            {
                if(ninter.OperationalStatus == OperationalStatus.Up)
                {
                    IPInterfaceProperties ipProperties = ninter.GetIPProperties();
                    IPAddressCollection dnsAddresses = ipProperties.DnsAddresses;
                    foreach(IPAddress dnsAdrs in dnsAddresses)
                    {
                        dnsServer = dnsAdrs.ToString();
                    }
                }
            }
            ip.SetNameservers(nic, dnsServer);  // Calling Method
            public_ip = new WebClient().DownloadString("http://icanhazip.com");
}

标签: c# winforms ip
1条回答
【Aperson】
2楼-- · 2019-06-13 17:57

How you've described your question is not how the internet (is supposed to) work(s).

Windows doesn't let you write raw IP packets, for this you need to use a TAP/TUN driver. But although you send out packets spoofing the source IP address, the internet between you and the destination won't return the route.

If you're operating behind a block of IP addresses, and only want to spoof another in that block, the return address will get back to your local router, but still won't necessary route back to you.

Unless you use TAP/TUN, there's no other way to steal someone else's Public IP address, excluding other network security vulnerability exploitations which are beyond the scope of this forum.

And even with TAP/TUN you're very limited in what you can achieve over spoofed IP packets in one direction. In fact, ISPs may filter out spoofed IP addresses.

查看更多
登录 后发表回答