Dns.GetHostEntry doesn't convert string which contains IP - c#

The function Dns.GetHostEntry doesn't handle ipaddresses as strings e.g. 127.0.0.1 but if I pass google.de as a parameter it works quite well.
Am I doing something wrong ?
public static Socket connSock(string Server, int Port)
{
Socket s = null;
IPHostEntry ipHE = Dns.GetHostEntry(Server);
//IPAddress[] ipA = null;
IPEndPoint ipE = null;
foreach (IPAddress address in ipHE.AddressList)
{
ipE = new IPEndPoint(address, Port);
Socket tempSocket = new Socket(ipE.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipE);
if (tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}

This could mean you're system is unable to get the host entry. This occurs (for instance) when there's no PTR record defined for the given IP.

Related

Save connected Socket in Dictionary

I'm trying to save a connected socket in a dictionary so my API doesn't have to create a new connection every time. My problem is that the socket gets disposed.
So when I call GetConnection() a second time socket.connected is false and socket.Available.Message is "Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'.".
public static class ModbusSocket
{
private static Dictionary<IPAddress, Socket> socketList;
public static Socket GetConnection(string server, int port)
{
if (socketList is null)
{
socketList = new Dictionary<IPAddress, Socket>();
}
IPAddress iPAddress = IPAddress.Parse(server);
if (socketList.ContainsKey(iPAddress))
{
var socket = socketList[iPAddress];
if (socket.Connected)
{
return socket;
}
else
{
socketList.Remove(iPAddress);
socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(iPAddress, port);
socket.Connect(ipe);
socketList.Add(iPAddress, socket);
return socket;
}
}
else
{
Socket socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(iPAddress, port);
socket.Connect(ipe);
socketList.Add(iPAddress, socket);
return socket;
}
}
}
OMG I found the issue...
I invoked it with using:
using (Socket s = ModbusSocket.GetConnection(hostIp, port))
{
var telegram = new Telegram();
telegram.Set(0, AddressConst.PositionWindow, 4);
var response = telegram.SendAndReceive(s);
var result = BitConverter.ToInt32(new byte[] { response.Byte19, response.Byte20, response.Byte21, response.Byte22 }, 0);
return result;
}

C# send custom socket string

I have this code:
public static List<Socket> samp = new List<Socket>();
IPHostEntry host = null;
Socket sock;
host = Dns.GetHostEntry(sending ip..);
foreach (IPAddress address in host.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, 7777);
sock = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(ipe);
if (sock.Connected)
{
samp.Add(sock);
}
}
This code work's okay. It send's my ip. How it looks in console:
How can I send custom string? For example i'm tried this code:
if (sock.Connected)
{
byte[] msg = Encoding.UTF8.GetBytes("This is a test");
byte[] bytes = new byte[256];
int i = sock.Send(msg);
MessageBox.Show(string.Format("Sent {0} bytes.", i));
samp.Add(sock);
}
It shows message: Sent 14 bytes. But in the console nothing prints.. How can I send this text to console? I'm also tried this:
sock.Send(Encoding.UTF8.GetBytes("This is a test"));
And this not prints :(
Thanks in advance !

Send socket before closing

I have this code:
public static List<Socket> samp = new List<Socket>();
Socket connection/etc in form load..
IPHostEntry host = null;
Socket sock;
host = Dns.GetHostEntry(sending ip..);
foreach (IPAddress address in host.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, 7777);
sock = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(ipe);
if (sock.Connected)
{
sock.SendTo(Encoding.UTF8.GetBytes("App starts"), ipe);
samp.Add(sock);
}
}
In form closing:
if (samp.Count > 0)
{
foreach (Socket socket in samp)
{
socket.Send(Encoding.UTF8.GetBytes("App closing"));
socket.Close();
}
}
And i'm getting error:
Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'
Thanks in advance!
P.S looks like socket.Close() works, but socket.Send nope :(

Why are clients connecting so slow?

I am trying to make a program in witch multiply clients will connect to the server. But i have a problem because when i try to connect more than 1 client at the same time, it takes a "long time" to do it.
i am using asynchronous way to connect:
public bool connect(string IP,int port)
{
try
{
if (m_clientSocket == null)
{
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(IP.ToString());
int iPortNo = System.Convert.ToInt16(port.ToString());
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
}
}catch()
{
return false;
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
if (m_clientSocket != null)
{
if (m_clientSocket.Connected)
{
client.EndConnect(ar);
// send next data here
}
else
{
client.EndConnect(ar);
m_clientSocket.Close();
m_clientSocket = null;
state = CONNECT_ERROR;
}
}
}
catch ()
{
}
}
For each client I want to connect I open a new class that includes two methods that you can see above. than with simple for loop I call methods one after another.
in Wireshark I observe the time that next needs to connect to a server is 0.1s witch I think is allot.
Any idea why does it take so long ?
Thanks for any kind of help.

Winforms C# app using sockets works under winXp, but throws error under Windows 7

Here's the properties and the method that connects.
protected Socket _socketConnection =
new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
private string _host = "";
private string _hostIpAddress = "";
private int _port = 0;
public void Connect()
{
// don't allow two connections
if (_socketConnection.Connected)
return;
// get the ip address from the hostname
IPHostEntry ipHostEntry = Dns.GetHostByName(_host);
_hostIpAddress = ipHostEntry.AddressList[0].ToString();
// create the socket endpoint
IPAddress ipAddress = IPAddress.Parse(_hostIpAddress);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, _port);
// connect
try
{
_socketConnection.Connect(ipEndPoint);
if (OnConnect != null)
OnConnect();
}
catch
{
throw;
}
}
When I run the app under Windows 7 I get the following error:
An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call.
I've seen messages that talk about setting a particular option on the socket, but this is an app that has been working for years and is only happening when this app is installed on Windows 7.
Is there a compatibility flag to tweak or something?
Thanks!
Perhaps on Win7 you get a IPv6 as the _hostIpAddress. Try using something like this when instantiating the socket:
if(Socket.OSSupportsIPv6 && _hostIpAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
// newer OS
_socketConnection = new Socket(
AddressFamily.InterNetworkV6,
SocketType.Stream,
ProtocolType.Tcp);
_socketConnection.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
} else {
// older OS
_socketConnection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}

Categories