The prog in c#:
private void listBox1_Click(object sender, EventArgs e)
{
String data = (String)this.listBox1.SelectedItem;
data = data.TrimEnd(new char[] { '\r', '\n' });
try
{
ip = Dns.GetHostAddresses(data);
}
catch (SocketException ex)
{
MessageBox.Show(ex.ErrorCode.ToString());
}
clientIP = new IPEndPoint(ip[0], 6000);
newSock.Bind(clientIP);
newSock.Listen(100);
resetEvent.Set();
}
In the above code, I obtain the ip-address of the remote host who is shown in the listbox and correspondingly in order to start accepting messages need to create an IPEndPoint(clientIP).
newSock is a variable of type socket initialized as:
newSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
The problem is in the line where I bind the socket newSock to the IPEndPoint clientIP where I am getting an error saying it is an invalid address.
However to cross check I tried to display the ip-address on a message box which it did correctly.
So what exactly is going wrong??
You shouldn't bind a socket to remote host address. It's used to indicate on which inbound IP address you should listen. You should either specify one of your own IP addresses (if you want to listen only on a single IP) or specify IPAddress.Any (0.0.0.0) to listen on all IP addresses you have.
By the way, if you want to connect to a remote address, you shouldn't use Bind at all. You'd just use the Connect method
Related
I'm working on a Wpf Socket
The messagebox is appers only when there is a problem with
the Ip address and port number.
After closing the messagebox I can't connected even I put proper Ip address and port number.
I have to restart the program to connect.
I like to try to re-connect by giving a new Ip address and prot number after without restrating the program
if (socketWatch == null)
{
dicScoket = new Dictionary<string, Socket>();
socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
IPEndPoint endPoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
socketWatch.Bind(endPoint);
socketWatch.Listen(20);
Listen();
Showmsg("Connected!");
}
catch (Exception error)
{
MessageBox.Show(" Error");
can't re-connect after closing messagebox
The problem is likely to be the socketWatch variable which is checked for being null before the connection attempt. The variable is initialized on the first attempt and remains not null ever after. Consider adding
socketWatch.Dispose();
socketWatch = null;
inside the catch block.
I have my Netduino Plus 2 go out to a web service to look up some values that I would like it to use in my project. One of the values that I have the Netduino check is its preferred IP address. If the Netduino has a different IPAddress than its preferred, I want to change it.
I have a method in my project called BindIPAddress (below) that takes a string.
I am getting a SocketException with a code of 10022 for invalid argument. This happens when I call this.Socket.Bind. My class has a property called Socket to hold the Socket value. Is it because my socket already has an endpoint ? I tried adding this.Socket = null and then this.Socket = new (....... thinking we need a new socket to work with, but this returned the same error.
Please advise how I can change my IP address from one static IP address to another.
public void BindIPAddress(string strIPAddress)
{
try
{
Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableStaticIP(strIPAddress, "255.255.240.0", "10.0.0.1");
Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableStaticDns(new string[] { "10.0.0.2", "10.0.0.3" });
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(strIPAddress), 80);
this.Socket.Bind(ep);
this.IpAddress = strIPAddress;
}
catch(SocketException exc)
{
Debug.Print(exc.Message);
Debug.Print(exc.ErrorCode.ToString());
}
catch(Exception ex)
{
Debug.Print(ex.Message);
}
//Debug.Print(ep.Address.ToString());
}
There may be 2 possible solutions to this problem. The first one is, you can programatically set the preffered IP addresses as the way you have tried to do so and the second one is, you can use MFDeploy tool, which comes with .NET Micro Framework SDK bundle that allows you to set your embedded device network configuration statically before running your application on it.
1) Since you have not provided rest of the code, here's a proper way to bind your socket to an EndPoint (actually, I would not design that class and binding function as the way you posted here, but just wanted to underline the missing parts of your code):
public void BindIPAddress(string strIPAddr)
{
Socket sock = null;
IPEndPoint ipe = null;
NetworkInterface[] ni = null;
try
{
ipe = new IPEndPoint(IPAddress.Parse(strIPAddr), 80);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Assuming the WebService is connection oriented (TCP)
// sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // if it broadcasts UDP packets, use this line (UDP)
ni = NetworkInterface.GetAllNetworkInterfaces();
if (ni != null && ni.Length > 0)
{
ni[0].EnableStaticIP(strIPAddr, "255.255.240.0", "10.0.0.1");
ni[0].EnableStaticDns(new string[2] { "10.0.0.2", "10.0.0.3" });
sock.Bind(ipe);
this.Socket = sock;
this.IpAddress = strIPAddr;
}
else
throw new Exception("Network interface could not be retrieved successfully!");
}
catch(Exception ex)
{
Debug.Print(ex.Message);
}
}
2) Or without programming, just by using MFDeploy tool you can set the preferred IP addresses after plugging your embedded device into your PC and following the path below:
MFDeploy > Target > Configuration > Network
then enter the preferred IP addresses. That's simply all.
For some reason the C# socket.RemoteEndPoint started returning the address of the default gateway. It used to work and I know the code hasn't changed. I'm not sure when it started occurring as the logs don't go back far enough so I'm not sure what could have happened to this server to cause this. Everything seems to be working normally. Just not getting the remote IP anymore.
Anyone have any idea what could cause this?
Here is the relevant code.
public void startClientListening(string ipString, int port)
{
IPAddress ip = IPAddress.Parse(ipString);
// Create the listening socket...
clientListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(ip, port);
// Bind to local IP Address...
clientListenerSocket.Bind(ipLocal);
// Start listening...
clientListenerSocket.Listen(32);
// Create the call back for any client connections...
clientListenerSocket.BeginAccept(onClientConnect, clientListenerSocket);
}
private void onClientConnect(IAsyncResult asyn)
{
Socket workerSocket = clientListenerSocket.EndAccept(asyn);
workerSocket.NoDelay = true;
//This returns 192.168.1.1 rather than the remoteIp
string remoteIp = ((IPEndPoint)workerSocket.RemoteEndPoint).Address.ToString();
}
This could happen if the default gateway was a router/ip firewall before but now it is a proxy/application firewall.
In this case the ip connection is instantiated by the proxy and therefore you see the ip address of the proxy and not of the real client.
I have a program shown below:
Socket receiveSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
EndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, 3838);
byte[] recBuffer = new byte[256];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
receiveSocket.Bind(bindEndPoint);
receiveSocket.Receive(recBuffer);
}
and it is working but when I want to just listen to a specific IP address it does not work,
it throws an exeption "the requested address is not valid in context"
new code:
EndPoint bindEndPoint = new IPEndPoint(IPAddress.Parse("192.168.40.1"), 3838);
The IP addresses you are binding to, should be one of the IP addresses that are actually assigned to the network interfaces on your computer.
Let's say you have an ethernet interface and a wireless interface
ethernet: 192.168.1.40
wireless: 192.168.1.42
When calling the Bind method on your socket, you are telling it on which interface
you want to listen for data. That being either 'any of them' or just the ethernet interface for example.
I'm guessing this is not what you are looking for?
Perhaps you are trying to restrict who can make a connection to your server
So whate you may be looking for is
var remoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.40"), 0)
receiveSocket.ReceiveFrom(buffer, remoteEndpoint);
This restricts the source from which you accept data.
While testing my Client-Server program, I encountered a weird exception when trying to connect to the server on a different router:
"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."
The client can connect to the server perfectly in the local network, however it doesn't work when it is over the internet.
I port forwarded port 1250 (the one I'm using), and using SimplePortForwarding (http://www.simpleportforwarding.com/) I verified that the port was open and working.
I based my implementation on this tutorial:
http://www.developerfusion.com/article/3918/socket-programming-in-c-part-1/
Any idea what is wrong?
Thanks!
Here is the server listen method:
public void startListening(int port)
{
lock(_locker)
{
_listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
// Bind socket to local endpoint, and listen for incoming connections
IPEndPoint ipEndpoint = new IPEndPoint(IPAddress.Any, port);
_listeningSocket.Bind(ipEndpoint);
_listeningSocket.Listen(10);
waitForNewClient();
// successfully started listening
_isListening = true;
} catch (SocketException e)
{
// failed for some strange reason
_isListening = false;
}
}
}
Here is the client connect code:
public String connect(String ipAddress, int port)
{
lock(_locker)
{
if (!_connecting)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
try
{
_socket.Connect(endpoint);
_connected = true;
waitForData();
_eventManager.queueEvent(new PlayerJoinedEvent(PlayerJoinedEvent.PLAYER_JOINED, name));
} catch (SocketException e)
{
// Exception is thrown HERE
return e.Message;
}
}
}
return "";
}
Make it sure that your Server IP address is public unless it is not reachable.
Check this link for private address spaces.
You opened port 1250 on the server or the client router? It needs to be opened on the server router. You may need to make sure your server is connected to your DMZ port and/or have DMZ enabled on your server router.
Hope this helps.
I Fixed the problem.
The IP Address I used was the internal ip address I got from ipconfig, but the IP address I needed to use was the external one, the one you get from services like http://www.whatsmyip.org/.
I'm still confused as to why these two numbers are different.