get unused IP address - c#

I need to get an available IP from the DHCP. I tried to get any ip address and start to ping the next until I reach one that doesn't respond.
public static IPAddress FindNextFree(this IPAddress address)
{
IPAddress workingAddress = address;
Ping pingSender = new Ping();
while (true)
{
byte[] localBytes = workingAddress.GetAddressBytes();
localBytes[3]++;
if (localBytes[3] > 254)
localBytes[3] = 1;
workingAddress = new IPAddress(localBytes);
if (workingAddress.Equals(address))
throw new TimeoutException("Could not find free IP address");
PingReply reply = pingSender.Send(workingAddress, 1000);
if (reply.Status != IPStatus.Success)
{
return workingAddress;
}
}
}
However, sometimes the DHCP reserves special address for some computers, so I need to get an available ip address from the dhcp.
How can I implement that in C#?

That is not the right way you are using it ,
you should request the DHCP server a new ip and then accept it ,
read about communicating with DHCP Server here
http://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol

A client application cannot make a request to the DHCP server for all available addresses.
A DHCP server can only process the following messages from a client:
DHCPDISCOVER
DHCPREQUEST
DHCPDECLINE
DHCPRELEASE
DHCPINFORM
Please see RFC 2131 - Dynamic Host Configuration Protocolfor additional information.
If you are running Windows DHCP server and you have access to the box, you can use Windows PowerShell Scripting to query the DHCP database.
Excerpt from Weekend Scripter: Parsing the DHCP Database? No Way!
Summary: Microsoft Scripting Guy, Ed Wilson, talks about a Windows PowerShell function from the DHCPServer module that permits parsing the DHCP database.

I found this app that solve the problem
http://www.centrel-solutions.com/support/tools.aspx?feature=dhcpapi

Related

Problem in running Open.NAT library for port forwarding

I am trying to use a library (Open.NAT) for port forwarding the problem is that i am getting an ip address that is not actually my external ip address and neither my port is getting forwarded
Here my External ip Address by this Library
My Actual Ip Address
I treid to 'ping' that external ip address on my pc and that works completely fine but when i do the same with any other pc (which is not connected on my network ) it doesn't respond
var discoverer = new NatDiscoverer();
var cts = new CancellationTokenSource(10000);
var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
var ip = await device.GetExternalIPAsync();
await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1600, 1700, "The mapping name"));
Console.WriteLine("The external IP Address is: {0} ", ip);
why this library is providing me wrong ip address & my port is not getting forwarded ?

Connecting peers in Lidgren from a server

I would like to set up a P2P matchmaking server. The situation is as follows:
I have 2+ peers behind NAT'd router(s).
I have a server behind a port-forwarded router on a static IP.
The server's job is to register the contact information of each peer, and send it any other peer when requested.
A peer could then query the server for a list of others, and directly connect to them.
Presently, peers can connect to the server, register their addresses, and query it for other peers' addresses. My issue is introducing the peers to each other.
I am presently getting the internal and external IP addresses of each peer like so. It is heavily based around the Master Server Sample that ships with Lidgren; however, that merely connects users to client/server sessions, while I require peer to peer.
//client code; getting our internal IP and sending it to the server
NetOutgoingMessage om = server_client.CreateMessage(); //create message on the server's connection
... //header
IPAddress mask;
var endpoint = new IPEndPoint(NetUtility.GetMyAddress(out mask), peer_client.Port); //gets the internal IP address
... //write message data and send to server
When the server gets a request, or when a peer is registered to the server, it gets that peer's external IP from the connection message. We then have access to both IPs from both peers when handling a request:
//server code, handling the peer request message:
...
string key = msg.ReadString();
Output("Requesting peer: " + key);
IPEndPoint requester_internal = msg.ReadIPEndPoint();
IPEndPoint requester_external = msg.SenderEndPoint;
//attempt to find requested user
User u = null;
if (Users.TryGetValue(id, out u))
{
IPEndPoint target_internal = u.IPInternal;
IPEndPoint target_external = u.IPExternal;
...
//send the requested IPs to the sender, and the sender's IPs to the target.
}
Now, the issue is how to connect the peers to each other using this information (or, whatever other information is required to make the connection), since the other infrastructure is already functional.
My first attempt was using the built-in Introduce method:
//server code, continuing from the above
//instead of directly sending IPs to users, introduce them ourselves
s_server.Introduce(target_internal, target_external, requester_internal, requester_external, key);
This seemed to work to some degree, but it connected to the server connection on each client instead of the peer connection, and only succeeded on the sender.
Attempting to manually connect with the sent IPs resulted in endless "attempting to connect" messages:
//peer code; handling 'other peer data received' msg
IPEndPoint peer_internal = msg.ReadIPEndPoint();
IPEndPoint peer_external = msg.ReadIPEndPoint();
Output("SERVER: Recieved peer IP. Attempting to connect to:\n" + peer_internal.ToString() + "\n" + peer_external.ToString());
NetOutgoingMessage om = peer_client.CreateMessage();
om.Write((Int32)3); //unique header for debugging purposes
peer_client.Connect(peer_external, om); //tried both internal and external, no dice
Lastly, a sample case of the IPs that I'm seeing, as dumped from the server:
P1 Internal: 169.xxx.xxx.xxx:14243 //local subnet address, using the proper port
P1 External: xxx.xxx.xxx.xxx:62105 //IP address of the system, matching that from any IP testing site, but using a seemingly random port
P2 Internal: 169.xxx.xxx.xxx:14243 //same as above for the second peer
P2 External: xxx.xxx.xxx.xxx:62106
I believe that the issue is that the peer connection's external port is randomly created somewhere along the line, instead of using that which I specify when creating it. As such, it can't be forwarded in advance. I would be happy with users being required to forward a specific port, as many P2P games work this way.
In other words, I seem to have everything that I need in order to get NAT punching working properly, but I lack the knowledge of Lidgren to make it happen.
Finally, here is how I set up my peer_client:
//peer code: initialize the connection to any other peers we may connect to later
NetPeerConfiguration pconfig = new NetPeerConfiguration(appidstr_client);
pconfig.Port = 14243; //properly forwarded in router
pconfig.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
pconfig.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
pconfig.AcceptIncomingConnections = true;
peer_client = new NetPeer(pconfig);
peer_client.Start();
Did you enable introduction messages using "config.EnableMessageType(NetIncomingMessageType.NatIntroductionSuccess);"?
Is "14243" a typo? In the sample the master server listens on 14343 and the clients listen on 14242.
"This seemed to work to some degree, but it connected to the server connection on each client instead of the peer connection, and only succeeded on the sender."
I don't understand what this means. If you're using the NetPeer class there's no specific "server connection"?
Remember IPEndPoint includes the port number, in case you're storing it away somewhere you might want to set it to the port you're trying to punch open.

TCP send a packet with External IP Source?

i will creat a valid TCP Packet (3 way handshake) to request on my server (real server online not vmware localhost)
My PC IP ADDRESS: 192.168.1.4
My ONLINE IP ADDRESS: 177.9.9.9
My Server IP ADDRESS: 113.x.x.x
I send a TCP Packet from my PC (177.9.9.9) to server (113.x.x.x) and success!
I can see this request showing in Wireshrak very clear with source IP is 177.9.9.9 and Destination ip is 113.x.x.x
i will write packet in C# with PCAP.NET and here is my ipV4Layer code!
IpV4Layer ipV4Layer =
new IpV4Layer
{
Source = new IpV4Address("192.168.1.4"), // My lan IP address
CurrentDestination = new IpV4Address("113.x.x.x"), // Server IP ADDRESS
HeaderChecksum = null, // Will be filled automatically.
Identification = 28104,
Options = IpV4Options.None,
Protocol = null, // Will be filled automatically.
Ttl = 128,
TypeOfService = 0,
};
NOW i want to ask, how to change 177.9.9.9 to another IP address? Not Proxy, Not socks, NOT VPN! I want to change my online IP to any IP ADDRESS, i just want to send a TCP SYN request like this and don't need server response any data, just send it with any IP address, how can do that or this way is Impossible?
Thanks for help!
If you really want to do some sort of load balancing then, go google the concept and research the viable options.
Here are some examples:
DNS based
Router/firewall/nat
Servicebus with queues, for a high level solution

how to find the ip address of client who is login to our website or browsing our website

Here i have a small problem, that i want to find out the IP Address of the client who is accessing my website, i tried so many but all these are giving me 127.0.0.1 as IP, while i am testing in local host,
Please some one provide the code snippet and help me,
Thanks in advance,
public string GetClientIP()
{
string result = string.Empty;
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
string[] ipRange = ip.Split(',');
int le = ipRange.Length - 1;
result = ipRange[0];
}
else
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return result;
}
This is to be expected, your localhost IP address will most of the time be 127.0.0.1.
As said in the comments, when you will deploy your site and remote clients access it, their actual IP will correctly be retrieved.
If you want to try locally, you can try to configure your local network so that a remote computer on the same network access your web site. There you should see the IP address of that computer (for instance: 192.168.x.x).

Get IPAddress from a hostname

I want to get IP address of a host on my aspx page using C#, I'm using DNS class methods to get these.
It worked fine locally, but when I deployed the solution on IIS7 it returned only the IP address assigned by ISP but I want local IP address of that machine.
Any suggestion?
Here is Example for this.
In this example we can get IP address of our given host name.
string strHostName = "www.microsoft.com";
// Get DNS entry of specified host name
IPAddress[] addresses = Dns.GetHostEntry(strHostName).AddressList;
// The DNS entry may contains more than one IP addresses.
// Iterate them and display each along with the type of address (AddressFamily).
foreach (IPAddress address in addresses)
{
Response.Write(string.Format("{0} = {1} ({2})", strHostName, address, address.AddressFamily));
Response.Write("<br/><br/>");
}
I'm fairly confident that you can not get the local 192.168.C.D address of the local machine like this.
This is because of security and visibility (NAT's etc).
If you are looking to uniquely identify a user. I would look to sessions or cookies.
When looking up the ip address in a public DNS, you will get the officiall IP address communicated outwards. If NAT is used and you want the internal address you have to connect to a DNS server which holds the internal IP addresses.
you can use this method...
public static String GetIP()
{
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if(string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
}

Categories