I am new in socket programming in c#. I just want to implement a simple program of listing all the IP address and port of the client requesting in the server. I have this code, no error but the gui not appearing upon starting the project. I already allow it through firewall and still no luck. Please help me thank you.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 9999);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ip);
socket.Listen(10);
Socket client = socket.Accept();
IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
dataGridViewSelectedUsers.Rows.Add(Convert.ToString(newclient.Address), Convert.ToString(newclient.Port));
}
}
}
try the below code will list requested ip to your listening server
UdpClient udpServer = new UdpClient(11000);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP); // listen on port 11000
//list received ip address
listbox.items.Add(remoteEP.Tostring);
}
Related
I'm trying to send UDP packets back and forth from a tablet and laptop. My problem is I can't send packets from my android tablet to my laptop. I can send packets from my laptop to itself using both 127.0.0.1 and it's local ip 10.1.10.xxx . I can also send packets from my laptop to the android tablet using it's ip 10.1.10.yyy. I can also send packets from the tablet to itself using both ip address 127.0.0.1 and 10.1.10.yyy. I don't think this is a router setting issue. I'm using code from https://forum.unity.com/threads/simple-udp-implementation-send-read-via-mono-c.15900/
Send Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System;
public class Send : MonoBehaviour {
public string IP;
public int port;
public void SendNetworkMessage(string message)
{
Debug.Log("Testing");
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress broadcast = IPAddress.Parse(IP);
Debug.Log("Created Socket");
byte[] sendbuf = Encoding.ASCII.GetBytes(message);
IPEndPoint ep = new IPEndPoint(broadcast, port);
s.SendTo(sendbuf, ep);
Debug.Log("Message Sent");
}
}
Receive Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System;
using System.Threading;
public class Receive : MonoBehaviour {
public int port;
UdpClient listener;
IPEndPoint groupEP;
Thread receiveThread;
public void Start()
{
receiveThread = new Thread(new ThreadStart(Listen));
receiveThread.IsBackground = true;
receiveThread.Start();
}
public void OnDisable()
{
if(receiveThread != null)
{
receiveThread.Abort();
}
listener.Close();
}
public void Listen()
{
listener = new UdpClient(port);
groupEP = new IPEndPoint(IPAddress.Any, port);
while (true)
{
try
{
Debug.Log("Waiting for broadcast");
byte[] bytes = listener.Receive(ref groupEP);
Debug.Log("Received broadcast from " + groupEP);
Debug.Log(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
}
catch (SocketException e)
{
Debug.Log(e);
}
}
}
}
Update:
I tested this in the android emulator using the same version of android as on the tablet and it works. I don't know of a setting on device where it could receive data but not send it.
I wrote a C# TCP Server that runs on my desktop, while I have a client running on my windows phone. It works great, the client can connect to the server. But I am trying to make it so the server can receive messages from the client. When I run it, the server just receives a number when I am sending a string.
Here is my server code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace TCPServer
{
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 80);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
TcpClient client = this.tcpListener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
Console.WriteLine("Got connection");
StreamReader clientStreamReader = new StreamReader(clientStream);
Console.WriteLine(clientStreamReader.Read());
}
}
}
Here is the client code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace NetworkingTesting
{
class Client
{
Socket socket = null;
static ManualResetEvent clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
DnsEndPoint hostEntry;
public string Connect(string hostName, int portNumber)
{
string result = string.Empty;
hostEntry = new DnsEndPoint(hostName, portNumber);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
result = e.SocketError.ToString();
clientDone.Set();
});
clientDone.Reset();
socket.ConnectAsync(socketEventArg);
clientDone.WaitOne(TIMEOUT_MILLISECONDS);
return result;
}
public void SendToServer(string message)
{
SocketAsyncEventArgs asyncEvent = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry};
Byte[] buffer = Encoding.UTF8.GetBytes(message + Environment.NewLine);
asyncEvent.SetBuffer(buffer, 0, buffer.Length);
socket.SendAsync(asyncEvent);
}
}
}
In my main client class, I have: client.SendToServer("hello!");
When I run the server and run the client the server detects the client but receives "104" instead of "Hello". Could anybody explain why this is happening and maybe provide a solution to the problem?
When you're doing clientStreamReader.Read() you're just reading one char as int from the stream. Check the doc here.
That's why you get only a number.
You need a delimeter to each message to know where it ends, \r\n is often used.
Here a sample to make your server receive your hello! String :
In your client Code
client.SendToServer("hello!" + "\r\n");
In your server Code
Console.WriteLine(clientStreamReader.ReadLine()); // Which should print hello!
When I run the program I get an invalid IP address error. I'm trying to have it so that users can put an IP address in the textbox and use that to send UDP packets. I don't know what is wrong with the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace ProjectTakedown
{
public partial class Form1 : Form
{
public Form1() //where the IP should be entered
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e) //button to start takedown
{
byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes("<Packet OF Data Here>");
string IP = "URL";
int port = 80;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SendTo(packetData, ep);
}
private void Stop_Click(object sender, EventArgs e)
{
}
private void URL_TextChanged(object sender, EventArgs e)
{
}
}
}
Somehow it's not reading the IP address.
Could it be this line perhaps?
string IP = "URL";
Don't you need to be able to dynamically inject the IP Address?
It should probably look something like this...
string IP = txtIPAddress.Text;
IP must be a string in dotted decimal notation (IPv4) or a colon-hex notation (IPv6)
Example:
127.0.0.1
::1
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.
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