Sending UDP Packet in C# - c#

I have a game server (WoW).
I want my players to download my custom patches to the game.
I've done a program that checks for update/downloading things.
I want my program to send a packet to my game server if player have all my patches. I dont need any response from the server, it will handle it, but its another story.
So I want to know, how to send a packet to a server.
Thank you!

Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPAddress serverAddr = IPAddress.Parse("192.168.2.255");
IPEndPoint endPoint = new IPEndPoint(serverAddr, 11000);
string text = "Hello";
byte[] send_buffer = Encoding.ASCII.GetBytes(text );
sock.SendTo(send_buffer , endPoint);

static void SendUdp(int srcPort, string dstIp, int dstPort, byte[] data)
{
using (UdpClient c = new UdpClient(srcPort))
c.Send(data, data.Length, dstIp, dstPort);
}
Usage:
SendUdp(11000, "192.168.2.255", 11000, Encoding.ASCII.GetBytes("Hello!"));

Related

Why do I get this error in the socket communication between Python and C#?

I have made a socket server in Python and a socket client in C#. Whenever an event occurs in the client, it sends a string, that comprises time information(hh:mm:ss:ffff) and either a negative or positive integer, to the server and they print out the string.
The problem is that the server sometimes prints out multiple event information at the same time, in the same line. For example:
//C# CLIENT OUTPUT
05:42:16:5942,-8
05:42:16:5962,+1
05:42:16:5972,+1
05:42:16:5992,-1
05:42:16:6002,-1
05:42:16:6023,-1
05:42:16:6043,-1
05:42:16:7856,-7
#Python SERVER OUTPUT
05:42:16:5942,-8
05:42:16:5962,+1
05:42:16:5972,+105:42:16:5992,-1 <- the error
05:42:16:6002,-1
05:42:16:6023,-1
05:42:16:6043,-1
05:42:16:7856,-7
I have no idea what causes the problem. Here' the source of the server and client.
#SERVER.py
from socket import *
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('localhost',999))
serverSocket.listen(1)
connectionSocket, addr = serverSocket.accept()
i = 0
sentence = ""
while True:
sentence = connectionSocket.recv(1024)
sentence = sentence.decode("UTF-8","ignore")
if sentence != "end":
print(sentence)
else:
print(sentence)
connectionSocket.close()
print("CLOSED")
break
//CLIENT.cs
string sendingValue;
static Socket sck;
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 999);
sck.Connect(localEndPoint);
// The below runs whenever an event occurs
string t = DateTime.Now.ToString("hh:mm:ss:ffff");
string userCount = GetUserRealCount().Trim();
sendingValue = t + "," + userCount;
byte[] data = System.Text.Encoding.ASCII.GetBytes(sendingValue);
sck.Send(data);

Irc client Identify protocol "No Ident repsonse"

My client isn't able to connect to the irc server I am trying to connect to. I did some research and it says that I need to listen on port 113 and respond back to the server in a certain format. I am not sure exactly how to do this. When I tried doing it before I got an error message. Here is the code before I tried listening. The irc sends the message to my client "No ident response". Do I need to create an entire different all together that will listen respond on port 113 or can I do it in here?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace ConnectIRC
{
class Program
{
static void Main(string[] args)
{
string ip = "asimov.freenode.net";
string nick = " NICK IKESBOT \r\n";
string join = "JOIN #NetChat\r\n";
int port = 6667;
const int recvBufSize = 8162;
byte[] recvbBuf = new byte[recvBufSize];
//stores the nick
byte[] nickBuf = Encoding.ASCII.GetBytes(nick);
//Stores the room join
byte[] joinBuf = Encoding.ASCII.GetBytes(join);
Socket conn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
conn.Connect(ip, port);
conn.Send(nickBuf, nickBuf.Length, SocketFlags.None);
conn.Send(joinBuf, joinBuf.Length, SocketFlags.None);
for(;;){
byte[] buffer = new byte[3000];
int rec = conn.Receive(buffer, 0, buffer.Length, 0);
Array.Resize(ref buffer, rec);
Console.WriteLine(Encoding.Default.GetString(buffer));
}
}
}
}
Despite #Saruman's answer above, you don't need to create an ident server to connect to most IRC networks (including freenode). You can completely ignore the error about "No ident response". It's an outdated technology which is no longer secure and only ever worked properly on Unix-based multiuser systems.
Your actual issue appears to be that you never finish registering the connection to the IRC server. The specification states that you need to send both USER and NICK messages:
string ip = "asimov.freenode.net";
string nick = "NICK IKESBOT \r\n";
// format is: USER <username> * * :<realname>
string user = "USER IKESBOT * * :IKESBOT\r\n";
string join = "JOIN #NetChat\r\n";
int port = 6667;
const int recvBufSize = 8162;
byte[] recvbBuf = new byte[recvBufSize];
//stores the nick
byte[] nickBuf = Encoding.ASCII.GetBytes(nick);
byte[] userBuf = Encoding.ASCII.GetBytes(user);
//Stores the room join
byte[] joinBuf = Encoding.ASCII.GetBytes(join);
Socket conn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
conn.Connect(ip, port);
conn.Send(nickBuf, nickBuf.Length, SocketFlags.None);
conn.Send(userBuf, userBuf.Length, SocketFlags.None);
conn.Send(joinBuf, joinBuf.Length, SocketFlags.None);
(You've got an extra space before the NICK - this may or may not break things.)
Aside:
You may find it easier to use TcpClient, StreamReader and StreamWriter to access the underlying socket - they wrap it and deal with the buffers for you. You can then read the response line by line directly into a string, and write to the socket by just passing a string. No fiddling around with encoding and buffers.
TcpClient client = new TcpClient("chat.freenode.net", 6667);
StreamReader reader = new StreamReader(client.GetStream());
StreamWriter writer = new StreamWriter(client.GetStream());
string recievedData = reader.ReadLine();
writer.WriteLine("NICK IKESBOT");
writer.Flush();
Yes you will need to create a totally separate port to listen on and respond back to ident requests
More information on ident can be found here

c# TCPclient set IP

I'm trying to send a packet using httpclient
TcpClient tc = new TcpClient(ip, 4500);
string s = "A7007000601D3B00";
byte[] arr = new byte[s.Length/2];
for ( var i = 0 ; i<arr.Length ; i++ ){
arr[i] = (byte)Convert.ToInt32(s.Substring(i*2,2), 16);
}
NetworkStream stream = tc.GetStream();
stream.Write(arr, 0, arr.Length);
tc.Close();
The problem is that it sends from port 47109, however i need to send the packet using port 46324. How do i set this?
There is an overload of the TcpClient constructor that allows you to bind it to a specific local IP address and port. See the documentation on MSDN.
The reason the example at Is there a way to specify the local port to used in tcpClient? is not working is probably because the first address on the list is not actually the local machine ip address. Something like this might fix the issue and pull the proper local IP address:
string remoteIP = "x.x.x.x";
IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).First();
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 47109);
TcpClient clientSocket = new TcpClient(ipLocalEndPoint);
clientSocket.Connect(remoteIP, 4500);

Get the IpAddress on which we received an UDP Multicast request

I'm using an UdpClient to read data from a multicast group.
It's configured like this:
m_udpClientReceiver = new UdpClient();
m_receivingEndPoint = new IPEndPoint(IPAddress.Any, m_port);
m_udpClientReceiver.ExclusiveAddressUse = false;
m_udpClientReceiver.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
m_udpClientReceiver.ExclusiveAddressUse = false;
m_udpClientReceiver.Client.Bind(m_receivingEndPoint);
m_udpClientReceiver.JoinMulticastGroup(m_multicastAddress, 255);
and I read it with:
Byte[] data = m_udpClientReceiver.Receive(ref m_receivingEndPoint);
I've several network cards(two LAN, one wifi), that are bound on differents subnets. I need to know on which network card(which ip in fact) the request has been received.
How can I achieve this?
Thank you!
As an alternative have you considered not joining a multicast group? You can send and receive multicast packets just as easily using the standard UDPClient class. i.e.
UdpClient.Send(byte[] dgram, int bytes, IPEndPoint endPoint)
where endPoint = new IPEndPoint(IPAddress.Broadcast, <port number>). And on the receive still using:
Byte[] data = m_udpClientReceiver.Receive(ref m_receivingEndPoint);
where m_receivingEndPoint is now correctly set? I've just tested this and it works fine.
I'm finally using the BeginReceive method(async), and I'm giving as context the ip on which it's bound

udp server respond on the basis of the request received from the udp client

I am making a UDP application in which I am able to receive the messages from udp client and sending a result back to the udp client...but now i want to set the udp server responses on the basis of the request...like for example if udp client send "Hello" message to the server then server reacts accordingly that if the client send "world" then server reacts accordingly that....In short my problem is that i am not able to read out the string which i am receiving at the server site.....this is window form application in c#
for example here is the code:
int recv;
byte[] data = new byte[1024];
IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1235);
Socket newsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
newsocket.Bind(endpoint);
MessageBox.Show("waiting for a client..");
IPEndPoint sen = new IPEndPoint(IPAddress.Loopback, 5001);
EndPoint tmp = (EndPoint)sen;
recv = newsocket.ReceiveFrom(data, ref tmp);
MessageBox.Show(" message recieved", tmp.ToString());
MessageBox.Show(Encoding.ASCII.GetString(data, 0, recv));
now i want to read out the string which i am receiving at the "recv" integer by which i could able to set the responses accordingly that..Please tell me How can i do that...
see this
link maybe it can help, your code seams to be rigth, but if it is not working try to change the encoding
to compare the data to string you need first convert it to an string with this line of code
Encoding.ASCII.GetString(data, 0, recv)
use like this
recv = newsocket.ReceiveFrom(data, ref tmp);
string receiver = Encoding.ASCII.GetString(data, 0, recv);
if (receiver == "Hello"){"do something"}

Categories

Resources