Socket communication error - c#

I'm making small program for socket communication in C#. Here're my codes:
Client (data sender):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Client
{
class Program
{
static Socket sck; //vytvor socket
static void Main(string[] args)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234); //nastav premennú loacalEndPoint na lokálnu ip a port 1234
try //Skús sa
{
sck.Connect(localEndPoint); // pripojiť
}
catch { //ak sa to nepodarí
Console.Write("Unable to connect to remote ip end point \r\n"); //vypíš chybovú hlášku
Main(args);
}
Console.Write("Enter text: ");
string text = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(text);
sck.Send(data);
Console.Write("Data sent!\r\n");
Console.Write("Press any key to continue...");
Console.Read();
sck.Close();
}
}
}
Server (data reciver):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Server
{
class Program
{
static byte[] Buffer { get; set; } //vytvor Buffer
static Socket sck;
static void Main(string[] args)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //vytvor Socket
sck.Bind(new IPEndPoint(0, 1234));
sck.Listen(80);
Socket accepted = sck.Accept();
Buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead]; //vytvor novú Array a jej dĺžka bude dĺžka priatých infomácii
for(int i=0; i<bytesRead;i++){
formatted[i] = Buffer[i]; //načítaj z Buffer do formatted všetky priate Bajty
}
string strData = Encoding.ASCII.GetString(formatted); //z ASCII hodnôt urob reťazec
Console.Write(strData + "\r\n"); //vypíš data
sck.Close(); //ukonči spojenie
}
}
}
My problem is: In client program I'm sending data on port 1234 to local ip. But I cannot connect. I have tried port 80 and it has connected. So please, where's my problem? How can I connect to everyone port? Please ignore comments in code and please help me.

You're listening on port 80, that is the port your client program should connect to. The "1234" is the LOCAL port the server is bound to. Nothing is listening on that port.

on which ip does the server listen? did you check with netstat -an | FIND "LISTEN" | FIND "1234"? (Note: replace listen with you language representation of it...).
0 may not be 127.0.0.1 but the first assigned IP adress of the first NIC... (although 0 should listen to all interfaces... but alas...
I would always use IP-adresses in both, the client and the server
hth
Mario

Related

Getting The requested address is not valid in its context. in my chat application

so I am coding a chat app in C# which is a console app where the user types the IPV4 address of the recipient. The problem is though, when tying in the IP address the message will come from returns this when not from localhost.
Message=The requested address is not valid in its context.
Source=System.Net.Sockets
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace SimpleTcpSrvr
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
int recv;
byte[] data = new byte[1024];
Console.WriteLine("You will need to recieve the password.txt file from your chat buddy.");
Console.WriteLine("");
Console.WriteLine("Please enter the IPv4 address of the buddy you are sending messages to.");
string rip = Convert.ToString(Console.ReadLine());
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(rip), 8080);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);
// This is where the error occurs.
newsock.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = newsock.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
string welcome = "Welcome to encrypted chat. Use ByteOribtPrivacyCannon to decrypt incoming messages.";
data = Encoding.UTF8.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);
string input;
while (true)
{
data = new byte[1024];
recv = client.Receive(data);
if (recv == 0)
break;
Console.WriteLine("Client: " + Encoding.UTF8.GetString(data, 0, recv));
input = Console.ReadLine();
Console.WriteLine("You: " + input);
client.Send(Encoding.UTF8.GetBytes(input));
}
Console.WriteLine("Disconnected from {0}", clientep.Address);
client.Close();
newsock.Close();
Console.ReadLine();
}
}
}
Why might this be happening? Thanks very much.
In fact, your code acts as a 'Server'. You need to listen to an address available on
your computer, but you are binding the IP address of another host.
The Server can only accept connections, it cannot choose Clients. But the Client can choose the Server.
You can try the following code to solve it.
Server:
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,8080);
Client:
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("172.xx.xx.xxx"),8080);
//172.xx.xx.xxx is the IPV4 address of your server computer

Client network and server network in c sharp

me and my friends are currently trying to build a chat application with c sharp in visual studio .
while doing that we bumped into the words "client network" and "server network" .
I ve been told that those are two dll files that provides a connection between my client , server and database . Can anyone explain to me what should these dll files contain and how to they contribute to our chat application ( I am still a beginner )
Thank you so much !
According to your description, you want to solve the communication between the client and the server.
I recommend that you use socket to realize the connection between server and client, and
create two DLL files to facilitate program reference.
It will be explained in detail below.
(1) ClientCommunication.dll
1: Establish a Socket object;
2: Use the Connect() method of the socket object to send the connection request to the server with the EndPoint object created above as a parameter;
3: If the connection is successful, use the Send() method of the socket object to send information to the server;
4: Use the Receive() method of the socket object to receive the information sent by the server;
5: Be sure to close the socket after the communication is over
(2) ServerCommunication.dll
1: Establish a Socket object;
2: Bind EndPoint with the Bind() method of the socket object;
3: Use the Listen() method of the socket object to start listening;
4: Accept the connection to the client, use the socket object's Accept() method to create a new socket object for communicating with the requesting client;
5: Use the new socket object to receive and send messages.
ServerCommunication.dll contains ServerSocket.cs
ServerSocket.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ServerCommunication
{
public class ServerSocket
{
static Socket serverSocket;
public static void StartListening(IPAddress ip, int port)
{
serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
IPEndPoint point = new IPEndPoint(ip, port);
serverSocket.Bind(point);
Console.WriteLine("{0}Listen Success", serverSocket.LocalEndPoint.ToString());
serverSocket.Listen(10);
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//clientSocket accept
byte[] result = new byte[1024];
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("Receive client{0}news{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
ClientCommunication.dll contains ClientSocket.cs
ClientSocket.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ClientCommunication
{
public class ClientSocket
{
static byte[] result = new byte[1024];
public static void StartClient(IPAddress ip, int port)
{
Socket socketClient = new Socket(SocketType.Stream, ProtocolType.Tcp);
IPEndPoint point = new IPEndPoint(ip, port);
try
{
socketClient.Connect(point);
Console.WriteLine("Successfully connected to server!");
}
catch
{
Console.WriteLine("Failed to connect to the server, please press enter to exit!");
return;
}
//clientSocket accept
int receiveLength = socketClient.Receive(result);
Console.WriteLine("Receive server message:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
// clientSocket send
try
{
Thread.Sleep(1000);
string sendMessage = "client send Message Hellp" + DateTime.Now;
socketClient.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("Send message to server:{0}" + sendMessage);
}
catch
{
socketClient.Shutdown(SocketShutdown.Both);
socketClient.Close();
}
Console.WriteLine("After sending, press enter to exit");
Console.ReadLine();
}
}
}
The specific use is as follows:
Server,cs code:
using ServerCommunication;
using System.Net;
namespace Server
{
class Server
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 8885;
ServerSocket.StartListening(ip,port);
}
}
}
Client.cs code:
using ClientCommunication;
using System.Net;
namespace Client
{
class Client
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 8885;
ClientSocket.StartClient(ip,port);
}
}
}
Operation results:
Server:
Client:

Displaying the IP address of the local machine in order to connect outside the network?

I'm trying to make a little simple server I can use between college and home. The server works fine, clients can connect. But I want to be able to connect from outside my local network. I'm trying to find a way to display the IP address of the machine required for connecting to it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace SocketProgramming
{
class Program
{
private static byte[] _buffer = new byte[1024];
private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static List<Socket> _clientSockets = new List<Socket>();
private static List<string> _nicknames = new List<string>();
static void Main(string[] args)
{
SetupServer();
Console.ReadLine();
}
private static void SetupServer()
{
Console.Write("Enter a port number to establish the server on: ");
int portNum = Int32.Parse(Console.ReadLine());
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, portNum));
_serverSocket.Listen(5);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
}
}
How do I get the IP address of the local machine? I want to be able to run this code on any machine, so using a static IP in the code won't help.
This post was extremely helpful for me when trying to tackle the same issue. My implementing code wound up using this answer with a slight modification to specifying exactly what Protocol type I wanted.
string localIP;
try
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIP = endPoint.Address.ToString();
}
}
catch (Exception ex)
{
localIP = String.Empty;
}
return localIP;
It is worth noting that a machine may have more than one IP address. You can get a quick list using the 'ipconfig' command from a dos or powershell cmd line. You can do something similar in c# like this:
foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces()) {
Console.WriteLine("Name: " + netInterface.Name);
Console.WriteLine("Description: " + netInterface.Description);
Console.WriteLine("Addresses: ");
IPInterfaceProperties ipProps = netInterface.GetIPProperties();
foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses) {
Console.WriteLine(" " + addr.Address.ToString());
}
Console.WriteLine("");
}
see: Get All IP Addresses On Machine
Additionally, if trying to reach a remote machine you could run into firewall/router issues. If your host ip is a non-routing address (like 10.*.*.*, or 192.168.*.*, etc.) you will not be able to reach it from outside of that network.

TCP/IP Client Socket Program in C#.Net Using IP Address And Port Number

TCP/IP Client Socket Program. Here My Main Requirement is Client Send Message and server receive message and store in database table in C#.Net, Using Server IP Address and Port Number.
You are talking about a simple Server-Client program.
What you need to do.
Create a server program and run it first
Create a client and connect to your running server using Connect("SERVER IP", PORT)
Now when client is connected to server, receive message to server and use database connections to store that message in database
Guides :
Write server -
http://csharp.net-informations.com/communications/csharp-server-socket.htm
Write client -
http://csharp.net-informations.com/communications/csharp-client-socket.htm
C# database access [SQL] -
http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm
UPDATE - As requested and as a guidance here is a working client and a server
CLIENT-
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace socket_prog
{
class Client
{
private static void Main(String[] args)
{
byte[] data = new byte[10];
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAdress = iphostInfo.AddressList[0];
IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 32000);
Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
client.Connect(ipEndpoint);
Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString());
byte[] sendmsg = Encoding.ASCII.GetBytes("This is from Client\n");
int n = client.Send(sendmsg);
int m = client.Receive(data);
Console.WriteLine("" + Encoding.ASCII.GetString(data));
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("Transmission end.");
Console.ReadKey();
}
}
}
SERVER-
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace socket_prog
{
class Server
{
static void Main(string[] args)
{
byte[] buffer = new byte[1000];
byte[] msg = Encoding.ASCII.GetBytes("From server\n");
string data = null;
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = iphostInfo.AddressList[0];
IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 32000);
ConsoleKeyInfo key;
int count = 0;
Socket sock = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
sock.Bind(localEndpoint);
sock.Listen(5);
while (true)
{
Console.WriteLine("\nWaiting for clients..{0}", count);
Socket confd = sock.Accept();
int b = confd.Receive(buffer);
data += Encoding.ASCII.GetString(buffer, 0, b);
Console.WriteLine("" + data);
data = null;
confd.Send(msg);
Console.WriteLine("\n<< Continue 'y' , Exit 'e'>>");
key = Console.ReadKey();
if (key.KeyChar == 'e')
{
Console.WriteLine("\nExiting..Handled {0} clients", count);
confd.Close();
System.Threading.Thread.Sleep(5000);
break;
}
confd.Close();
count++;
}
}
}
}
Run server first. Then run client.
you can get help from this below mentioned link
https://www.c-sharpcorner.com/article/socket-programming-in-C-Sharp/

UDP Listener respond to client

I found this great code on MSDN for a UDP Client/Server connection, however the client can only send to the server, it cant reply back. How can I make this so the server can respond to the client that send the message.
The Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Security.Cryptography;
namespace UDP_Server
{
class Program
{
private const int listenPort = 11000;
private static void StartListener()
{
bool done = false;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
while (!done)
{
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine("Received broadcast from {0} :\n {1}\n",groupEP.ToString(), Encoding.ASCII.GetString(bytes, 0, bytes.Length));
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
public static int Main()
{
StartListener();
return 0;
}
}
}
And the client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Security.Cryptography;
namespace UDP_Client
{
class Program
{
static void Main(string[] args)
{
Send("TEST STRING");
Console.Read();
}
static void Send(string Message)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress broadcast = IPAddress.Parse("10.1.10.117");
byte[] sendbuf = Encoding.ASCII.GetBytes(Message);
IPEndPoint ep = new IPEndPoint(broadcast, 11000);
s.SendTo(sendbuf, ep);
}
}
}
Just do it the other way round. Call StartListener on the client and it can receive udp data like a server.
On your server just send data with the clients code.
It's the same code, just with reversed roles. The client needs to listen on some port, and the server sends the message to the client's endpoint instead of the broadcast address.

Categories