How to check remote IP and Port is available? - c#

I have to check remote IP and Port is available or not.If its is available it will move to next form.If not available it should come to the initial state.I tried using this
while (true)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
-------
-------
-------
}
I am showing the example coding.it was checking local IP and port and moving to next form.it will check local port and IP is available.if port and IP not available it will come to the initial stage and it was working fine.same thing i have to check in remote Port and IP.

Use the Ping class of .NET to find out if the system is up and connected, the use the PortScanner to check if the port is open. check these links for further reading and exploring.
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping%28v=vs.110%29.aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/8e4410bd-307f-4264-9575-cd9882653945/help-with-portscanner-in-c?forum=csharpgeneral
OR
public static bool PingHost(string hostUri, int portNumber)
{
try
{
using (var client = new TcpClient(hostUri, portNumber))
return true;
}
catch (SocketException ex)
{
MessageBox.Show("Error pinging host:'" + hostUri + ":" + portNumber.ToString() + "'");
return false;
}
}

Related

how to connect webserver on other PC in same wifi?

I have Http server running on my PC, I can use localhost or 192.168.1.69 talk to the server.
I have a tablet in the same wifi as the PC, when I do 192.168.1.69:8080/hello
I don't get any response.
I tried set up port forwarding on router, added .exe to firewall trust, also tried use public ip(that open router login page) with port number. but they doesn't help,
public HttpServer(int port)
{
if (!HttpListener.IsSupported)
{
// Requires at least a Windows XP with Service Pack 2
throw new NotSupportedException(
"The Http Server cannot run on this operating system.");
} // end if HttpListener is not supported
_httpListener = new HttpListener();
_httpListener.Prefixes.Add("http://localhost:" + port + "/");
_httpListener.Prefixes.Add("http://192.168.1.69:" + port + "/");
_resourceLocator = new Locator();
}
public void Start()
{
if (!_httpListener.IsListening)
{
_httpListener.Start();
_running = true;
_connectionThread = new Thread(new ThreadStart(this.ConnectionThreadStart));
_connectionThread.Start();
}
}

Pinging an IP and port with C# [duplicate]

I have to check remote IP and Port is available or not.If its is available it will move to next form.If not available it should come to the initial state.I tried using this
while (true)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
-------
-------
-------
}
I am showing the example coding.it was checking local IP and port and moving to next form.it will check local port and IP is available.if port and IP not available it will come to the initial stage and it was working fine.same thing i have to check in remote Port and IP.
Use the Ping class of .NET to find out if the system is up and connected, the use the PortScanner to check if the port is open. check these links for further reading and exploring.
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping%28v=vs.110%29.aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/8e4410bd-307f-4264-9575-cd9882653945/help-with-portscanner-in-c?forum=csharpgeneral
OR
public static bool PingHost(string hostUri, int portNumber)
{
try
{
using (var client = new TcpClient(hostUri, portNumber))
return true;
}
catch (SocketException ex)
{
MessageBox.Show("Error pinging host:'" + hostUri + ":" + portNumber.ToString() + "'");
return false;
}
}

unable to connect with a Server over the WAN using Client Server approach?

I am working on simple Client Server Application, it is just like a chat Messenger.
I am using Client Server approach. My application works fine on LAN Local Area Network.but when it try to communicate to sever out side the LAN. Then there is no response to Client. while i know the server IP Address (through an external means ) which uses a broad band connection and resides on a WAN.
i think i am unable to resolve the IP address, or proxy like problem occurs.
Can anybody Help me out ?
Regards !
Sm.Abdullah
//
/* Server Program */
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class serv {
public static void Main() {
try {
IPAddress ipAd = IPAddress.Parse("172.21.5.99");
// use local m/c IP address, and
// use the same in the client
/* Initializes the Listener */
TcpListener myList=new TcpListener(ipAd,8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint );
Console.WriteLine("Waiting for a connection.....");
Socket s=myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b=new byte[100];
int k=s.Receive(b);
Console.WriteLine("Recieved...");
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
myList.Stop();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
---------------------------------------------------------------------------
/* Client Program */
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class clnt {
public static void Main() {
try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
// here is local ip..
// if i replace it with WAN IP it does not communicate.
tcpclnt.Connect("172.21.5.99",8001);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba,0,ba.Length);
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
Have you checked the firewall / router?
Most of the time unsolicited incoming connections are dismissed and will fail because they could be malicious in origin and nature.
You can however get around some of these issues by looking into NAT traversal
see: tcp client to communicate with server present in different network (NAT issue)

C# Listenin 5060 Port [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Listening to Port 5060
I am developing a SIP client.And I have a question.
I want listen 5060 port for catch the SIP Server Message.For this,I coding something.(Also I take admin rights in program)
But I get SocketException: "An attempt was made to access a socket in a way forbidden by its access permissions" (Native error code: 10013)...
My Code:
private void ListenPort() {
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
TcpListener server = null;
Int32 port = 5060;
IPAddress localAddr = IPAddress.Parse("192.168.1.33");
server = new TcpListener(localAddr, port);
Byte[] bytes = new Byte[1000];
String data = null;
while (hasAdministrativeRight == true)
{
server.Start();
int i = 0;
while (1==1)
{
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
data = null;
i = stream.Read(bytes, 0, bytes.Length);
data += System.Text.Encoding.ASCII.GetString(bytes, 0, i);
label3.Text += data;
this.Refresh();
Thread.Sleep(500);
}
}
}
Where do you think the problem?
Have you checked that no other program is already using port 5060? That's what this error can mean.
See this discussion on the matter: http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/d23d471c-002a-4958-829e-eb221c8a4b76/
You need to call server.Start() outside the while loop and before the first AcceptTcpClient call.
Also try using IPAddress.Any instead of IPAddress.Parse("192.168.1.33") for your listener ip
Make sure any other SIP Server program not installed as a Windows service which has using according port.
Type in netstat -an and it will show you the “listening” ports or try to googling port check softwares.
And check your SIP Server configuration for is it running over TCP or UDP.

Setting IP with a c# tool

I'm a c# newby who want to learn more about programming. So I started with a simple tool, wich can set the address of a choosen network adapter to static or dynamic (like the Windows TCP/IP Properties. I set the tool's design exactly like the TCP/IP Properties).
Setting a static IP address to the network adapter works pretty good.
But when I disconnet the Computer form the network and then set the network adapter's IP to dynamic (Obtain an IP address automatically"), it won't set the Windows IP Propertie to dynamic. I'm totaly lost with this problem, I have no idea how to solve it.
I understand that I only get an IP address automatically, when I'm connected to a network (where a router or a DHCP server is enabled).
But when I disconnect the computer form the network, an I set the IP Properties to dynamic with the the Windows TCP/IP Properties, it works well. What is worng in my code?
Thanks a lot for your help!
Below the code I'm using:
public void setDHCPMode()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (!(bool)mo["ipEnabled"])
continue;
try
{
string desc = (string)(mo["Description"]);
if (desc == NICcomboBox.Text)
{
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = null;
ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
toolStripStatusLabel1.Text = "DHCP set";
}
catch (Exception ex)
{
MessageBox.Show("Unable to set DHCP : " + ex.Message);
}
}
}
I found the problem. It looks like the WMI dosn't work correctly. It's impossible to set the TCP/IP Properties to DHCP, while the cable is unplugged for the specific NIC.
I solved it, through setting DHCP mode in the regestry. Now it works perfectly.

Categories

Resources