Code server I have server listen on port 1450:
//Using UDP sockets
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
EndPoint ourEP = new IPEndPoint(IPAddress.Any, 1450);
//Listen asynchronously on port 1450 for coming messages (Invite, Bye, etc).
clientSocket.Bind(ourEP);
//Receive data from any IP.
EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
byteData = new byte[1024];
//Receive data asynchornously.
clientSocket.BeginReceiveFrom(byteData,
0, byteData.Length,
SocketFlags.None,
ref remoteEP,
new AsyncCallback(OnReceive),
null);
but code on not open port 1450 and client connect:
otherPartyIP = new IPEndPoint(IPAddress.Parse(txtCallToIP.Text), 1450);
otherPartyEP = (EndPoint)otherPartyIP;
When i run code client and server in lan network it's ok. but run over network i check port 1450 in lan not open. tell me how open port 1450 in code server? thanks
Related
I have Thrift client-server application C# client and Python server. All in the same machine-Windows7. Debugging into the Thrift code I saw the client's socket cannot connect to the server's local server. BTW, The same C# client connects to C+ server and python and c++ clients connect to the same python server. Just C#-->Python combination fails.
The problem looks similar to Connecting Python SocketServer with C# Client. I tried to modify the code following the answer in the link above but still, C# socket throws "No connection could be made because the target machine actively refused it 127.0.0.1:9091"
Client(C#):
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[1];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
Socket client = new Socket(ipAddress.AddressFamily,SocketType.Stream,
ProtocolType.Tcp);
TcpClient tcpClient = new TcpClient(AddressFamily.InterNetwork);
tcpClient.Client = client;
tcpClient.Connect(ip, port);
Why ipHostInfo.AddressList[1]? This selection takes IPv4 adapter from
ipconfig. I tries other indices as well. Server(Python, Inside
to Thrift-sever library):
res0 = socket.getaddrinfo(self.host,
self.port,
self._socket_family,
socket.SOCK_STREAM,
0,
socket.AI_PASSIVE |
socket.AI_ADDRCONFIG)
...
self.handle = socket.socket(res[0], res[1])
self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(self.handle, 'settimeout'):
self.handle.settimeout(None)
self.handle.bind(res[4])
self.handle.listen(self._backlog)
client, addr = self.handle.accept()
It never exits from accept in case of C# client
You have too much duplicate code. Try following :
//client
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[1];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(remoteEP);
//Server
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);
TcpListener listener = new TcpListener(localEP);
listener.Start();
I have web App and the App has thermal printer with static IP and port
Through service
My Code C# :
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
//ReuseAddress : Allows the socket to be bound to an address that is already in use.
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
socket.Connect(remoteEP);
socket.SendTimeout = 2000;
socket.ReceiveTimeout = 2000;
socket.Send(data, data.Length, SocketFlags.None);
socket.Receive(data);
//The shutdown function Disables sends and receives on a Socket.
socket.Shutdown(SocketShutdown.Both);
//Closes the socket connection and allows reuse of the socket.
socket.Disconnect(true);
//Closes the Socket connection and releases all associated resources.
socket.Close();
But Some Time Socket NOT Close and i cant create new socket with printer
So how i check if socket not close and if open how close it before create new socket ????
plz help me !!
I have some client-server socket code that I want to be able to construct and (re)connect to periodically the same endpoint address: localhost:17999
Here is the server:
// Listen for a connection:
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Loopback, 17999);
Socket listener = new Socket(IPAddress.Loopback.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
listener.Bind(localEndPoint);
listener.Listen(1);
// Accept the connection and send a message:
Socket handler = listener.Accept();
byte[] bytes = new byte[1024];
bytes = Encoding.ASCII.GetBytes("The Message...");
handler.Send(bytes);
// Clean up
handler.Shutdown(SocketShutdown.Both);
handler.Close();
handler.Dispose();
listener.Shutdown(SocketShutdown.Both);
listener.Close();
listener.Dispose();
And here is the client:
byte[] bytes = new byte[1024];
Socket receiver = new Socket(IPAddress.Loopback.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
receiver.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiver.Connect(new IPEndPoint(IPAddress.Loopback, 17999));
int num_bytes_received = receiver.Receive(bytes);
string result = Encoding.ASCII.GetString(bytes, 0, num_bytes_received);
receiver.Shutdown(SocketShutdown.Both);
receiver.Close();
receiver.Dispose();
When I create the client and server for the first time, it works fine. However when I create it again, I get an error:
"A request to send or receive data was disallowed because the socket is
not conne cted and (when sending on a datagram socket using a sendto
call) no address was supplied"
I would like to be able to spin up this mechanism arbitrarily whenever I need to with the following order of events:
Launch the server and wait to accept a connection
Launch the client and connect to the server
Accept the client connection at the server
Send a message to the client
Repeat when necessary
How can I do this?
Thx in Advance!
EDIT: Each time I build the client and server objects it is from a different process.
You have two issues:
1) You're closing the listener. Just leave it open.
2) You're setting ReuseAddress on the wrong socket and way too late. Set it on the listening socket before you call bind (since that's when you use the address).
Setting ReuseAddress on a socket you aren't going to bind doesn't do anything. You can remove that from the client.
I tried what Gene suggested and it seems to work:
// Listen for a connection:
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Loopback, 17999);
using (Socket listener = new Socket(IPAddress.Loopback.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
listener.Bind(localEndPoint);
listener.Listen(1);
Thread t = new Thread(() =>
{
// Accept the connection and send a message:
using (Socket handler = listener.Accept())
{
byte[] bytes = new byte[1024];
bytes = Encoding.ASCII.GetBytes("The Message...");
handler.Send(bytes);
}
});
t.Start();
t.Join();
}
Thanks, all!
I am trying to fetch the IP address from the broadcast packets sent by a DSL modem and received on port 137 using UDP protocol. I am able to read the IP address when connectivity is present.
However, in unidentified network state, when my modem is configured for DHCP, and a specific range of IPs are allowed, and setting on my machine is auto-detect:
I get the default Local IP Address of the machine on reading the broadcast messages. That would be starting with 169.
Note: I am restarting the modem in order to receive the broadcast messages.
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 137);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
int iLoopCount=0;
while (iLoopCount <= 10000)
{
Console.WriteLine("Ready to receiveā¦");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.Default.GetString(data, 0, recv);
Console.WriteLine("{1}: from: {0}",((IPEndPoint)ep).Address.ToString(),DateTime.Now.ToString());
iLoopCount++;
// Console.WriteLine(sock.RemoteEndPoint.ToString());
}
sock.Close();
Console.Read();
Found the answer to my question at
http://www.codeproject.com/Articles/17031/A-Network-Sniffer-in-C
I created an application with server and client tool using sockets etc. When using my code on my computer works. Now I installed the Himachi software and I need to use this software in my application so that when a user connects with me, the application created could be used in this network. Note that this is my first time using sockets. The problem is that they are not connecting to each other and also it gives me this error on changing the ip and port: The requested address is not valid in its context
The send Tool
public Send(string Group, string port, string ttl, string rep, string data)
{
IPAddress ip;
try
{
Console.WriteLine("Send on Group: {0} Port: {1} TTL: {2}", Group,port,ttl);
ip = IPAddress.Parse(Group);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, int.Parse(ttl));
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(Group),int.Parse(port));
Console.WriteLine("Connecting...");
s.Connect(ipep);
byte[] byData = System.Text.Encoding.ASCII.GetBytes(data);
s.Send(byData, SocketFlags.None);
Console.WriteLine("Closing Connection...");
s.Close();
}
catch(System.Exception e) { Console.Error.WriteLine(e.Message); }
}
The Receive tool
public string RecvData(string Group, string port)
{
string str = "";
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, int.Parse(port));
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(Group);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip,IPAddress.Any));
// Getting the data
byte[] buffer = new byte[1024];
int iRx = s.Receive(buffer);
str = System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length);
// Closing a Socket
s.Close();
return str;
}
Thanks
So your problem is that you are trying to use a VPN (hamachi) to connect two apps the server and the client so that the client can receive messages from the server right? I think that the error given "The requested address is not valid in its context" is because you are using a VPN but I don't know how this can be solved sorry. What I think is that maybe you might also need the network id and password but again I'm not sure. Please keep us informed because this is a very interesting question.