Exception in opening a socket at my IP address - c#

I am new in socket programming C#. I am trying to make a chat server between two computers but I am unable to do that because I cant start my Socket..... I gave the Server Program my IP address but gives me an exception... "The requested address is not valid in its context" ...Here is the code:
IPAddress hostIPAddress = IPAddress.Parse("178.189.27.85");
TcpListener serverSocket = new TcpListener(hostIPAddress, 8888);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
string serverResponse = "Last Message from client" + dataFromClient;
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
Client program
try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.128.1",8888);
// 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);
}

IPAddress hostIPAddress = IPAddress.Parse("178.189.27.85");
Is your computer actually on the public internet? I would expect your computer to have a private IP (eg 192.168.x.y, 172.16-32.x.y, 10.x.y.z) unless it is directly connected to your internet connection.
Assuming you're on Windows, use a Command Prompt and run ipconfig, or visit Control Panel and look for your network settings. On Windows 7 for instance it's in the Network and Sharing Center, under "Change adapter settings"; look for the active adapter, right click and choose "Status".
Once you find your local IP address, use that. Or you can use 0.0.0.0 as a wildcard address – in effect saying "Just accept connections from wherever, I don't care what my IP address is."

Related

C# TCP Chat Working On Localhost But Message Is 0 Or Null On Other IP Addresses?

So my TCP C# client server, an oddity is happening, when the server sends a message to a client running on localhost 127.0.0.1, the message goes through no problem, but when sending the message to a client running on another IPv4, the client and server connect but the message is received as null or zero. I am wondering why the message would come through no problem on localhost, but connect and then recieve a null message on a different ip though they connect?
Server code:
{
{
{
try
{
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //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();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The message " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8001);
listener.Start();
Console.WriteLine("Listening on port: 8001");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
void HandleConnection(TcpClient client)
{
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
string buddylist = myList.ToString();
socketlist = s.ToString();
slist = char.Parse(socketlist);
foreach (char slist in buddylist)
{
void HandleConnection(TcpClient client)
{
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
while (connectedbuddies > 1)
{
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
}
}
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
}
}
Client code:
try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(RecieveIPAdd.Text, 8001); // use the ipaddress as in the server program
MessageBox.Show("Connected");
Stream stm = tcpclnt.GetStream();
MessageBox.Show("Listening for information......");
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string atk = Encoding.UTF8.GetString(bb.AsSpan(0, k));
Console.WriteLine($"Connected to server at IPv4 address {RecieveIPAdd.Text} Attack command Received: {atk}.
Thank you so much, I don't know why this would happen on an IP that is not localhost?

NetworkStream.Read() doesn't work and throws ArgumentOutOfRangeException

Just trying to create a chat server-client
This is the server waiting for a client connection (optional)*
TcpListener serverSocket = new TcpListener(8888);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
Then, the client connects to the server (optional)*
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect("127.0.0.1", 8888);
Then, on the client side, I send the message from a windows form, and the button click event does this:
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
//this goes to the server ------> to the part (4)
//returning from the server <------
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
textBox2.Text = "";
textBox2.Focus();
Finally, on the server side, an infinite bucle for client requests. And here is where I got the problem on the networkStream.Read()
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
if (networkStream.DataAvailable)
{
**networkStream.Read(bytesFrom, 0, (int) clientSocket.ReceiveBufferSize);**
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
string serverResponse = "Last Message from client" + dataFromClient;
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
I debugged step by step (on server and client), and it's all fine until I get to the networkStream.Read() method, and throws ArgumentOutOfRangeException... Please, anybody help me or tell me where the error is.
*I say optional because the 1. and 2. steps are fine (at least, I think)
From the MSDN, ArgumentOutOfRangeException means that offset or count is negative(2nd and 3rd parameters), OR the "size(count)" parameter is greater than the length of buffer minus the value of the "offset" parameter.
I'd try passing bytesFrom.Length as opposed to clientSocket.ReceiveBufferSize.

Socket communication output issue

In getting used to Sockets using Client server communication here is my code.
//server partl
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8020);
/* Start Listeneting at the specified port */
myList.Start();
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
//Console.WriteLine("Recieved...");
//Writes to label1
for (int i = 0; i < k; i++)
label1.Text = b[i].ToString();
//ASCII endoing to use ACK.
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 ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
//Client part
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1", 8020); // use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
//gets the text from textbox
String str = textBox1.Text;
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 ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
}
I am using a form to communicate on local host and writing a one .cs file and want to show the text(from textbox) from Client-labelled portion to the label on server-labelled portion.
Any idea why its not showing output?. New to sockets !!!
When socket receives the data instead of loop simply use this:
if (k > 0)
label1.Text = Encoding.UTF8.GetString(b);
Also you can use this for simply send and receive data using TcpClient which is a wrapper around socket.

how to send and receive string continously using sockets in c#

Basically what i am stuck at is , i want my client to send data continously and server to read from client as it sends, like when i send "2" it should read "2" and display and so on it should continue to read as long as i send from the client, i can stop or exit whenever i press some different character,.
what i have acheived is not continous, i send from client 2 and server receives 2 and then it is stopped, i want to send them continously , i am pasting below my code,
client.cs
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Client
{
class Program
{
const int port = 8001;
const string ip = "127.0.0.1";
const int maxBuffer = 100;
static void Main(string[] args)
{
try
{
while (true)
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1", 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]));
Console.ReadLine();
tcpclnt.Close();
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
server.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Server
{
class Program
{
const int port = 8001;
const string ip = "127.0.0.1";
const int maxBuffer = 100;
static void Main(string[] args)
{
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
// use local m/c IP address, and
// use the same in the client
while (true)
{
/* 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");
Console.ReadLine();
/* clean up */
s.Close();
myList.Stop();
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
Any help will be appreciated
Thanks :)
By using MultiThread you can send and receive message between client and server continuously.
Server side example:
IPAddress[] ipAdd = Dns.GetHostAddresses("192.168.1.38");
IPAddress ipAddress = ipAdd[0];
TcpListener serverSocket = new TcpListener(ipAddress, 8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
notifyIcon.ShowBalloonTip(5000, "Server Notification", " >> Server Started.", wform.ToolTipIcon.Info);
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
if (clientsList.ContainsKey(dataFromClient))
{
continue;
}
else
{
clientsList.Add(dataFromClient, clientSocket);
}
string onlineUsers = "";
foreach (DictionaryEntry item in clientsList)
{
onlineUsers += item.Key.ToString() + ";";
}
onlineUsers = onlineUsers.Remove(onlineUsers.Length - 1);
Broadcast.BroadcastSend(dataFromClient + " joined. |" + onlineUsers, dataFromClient, ref clientsList, false, false);
notifyIcon.ShowBalloonTip(5000,"Client Notification", dataFromClient + " joined.", wform.ToolTipIcon.Info);
HandleClient client = new HandleClient();
client.StartClient(clientSocket, dataFromClient, clientsList, notifyIcon);
}
More details
Ignore my earlier answer
The problem is that the server is waiting for user response in console after sending acknowledgement.
Console.ReadLine();
Just comment out this line in your original program.
And add a exit condition by checking the input.
Also as the previous poster suggest, make it thread based if you want multiple clients connecting to this server simultaneously.

c# udp client-server echo program

I just started socket programming in c#. I wanted to develop a simple client-server echo application. The problem I encountered is when i try to echo the message back to the client, it does not receive it. I spent a lot of time searching for solution on variety of forums but i couldn't find any that would help me with my problem.
Thanks in advance.
Andrew
Here is the code:
Server:
static void Main(string[] args)
{
string data = "";
UdpClient server = new UdpClient(8008);
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine(" S E R V E R IS S T A R T E D ");
Console.WriteLine("* Waiting for Client...");
while (data != "q")
{
byte[] receivedBytes = server.Receive(ref remoteIPEndPoint);
data = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
Console.WriteLine("Message Received " + data.TrimEnd());
server.Send(receivedBytes, receivedBytes.Length,remoteIPEndPoint);
Console.WriteLine("Message Echoed to" + remoteIPEndPoint + data);
}
Console.WriteLine("Press Enter Program Finished");
Console.ReadLine(); //delay end of program
server.Close(); //close the connection
}
}
Client:
static void Main(string[] args)
{
string data = "";
byte[] sendBytes = new Byte[1024];
byte[] rcvPacket = new Byte[1024];
UdpClient client = new UdpClient();
IPAddress address = IPAddress.Parse(IPAddress.Broadcast.ToString());
client.Connect(address, 8008);
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("Client is Started");
Console.WriteLine("Type your message");
while (data != "q")
{
data = Console.ReadLine();
sendBytes = Encoding.ASCII.GetBytes(DateTime.Now.ToString() + " " + data);
client.Send(sendBytes, sendBytes.GetLength(0));
rcvPacket = client.Receive(ref remoteIPEndPoint);
string rcvData = Encoding.ASCII.GetString(rcvPacket);
Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
Console.WriteLine("Message Received: " + rcvPacket.ToString());
}
Console.WriteLine("Close Port Command Sent"); //user feedback
Console.ReadLine();
client.Close(); //close connection
}
I was able to get this working by making the client talk directly to the server instead of broadcasting:
var serverAddress = "127.0.0.1"; // Server is on the local machine
IPAddress address = IPAddress.Parse(serverAddress);
...unless I'm missing an important reason why you were using broadcast in your original code?

Categories