Running this code on windows 10/11 using .NET 7.0 or any previous framework I got exception on line :
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
Unhandled exception. System.Net.Sockets.SocketException (10042): An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call.
at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, Boolean disconnectOnFailure, String callerName)
at System.Net.Sockets.Socket.SetMulticastOption(SocketOptionName optionName, MulticastOption MR)
at MainClass.Main(String[] args)
string IpGroup = "224.0.224.1";
string sPort = "2405";
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, int.Parse(sPort));
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(IpGroup);
try
{
//Error HERE
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
Console.WriteLine("Joined: " + IpGroup + ":" + sPort);
while (true)
{
byte[] b = new byte[100];
s.Receive(b);
string str = System.Text.Encoding.ASCII.GetString(b, 0, b.Length);
Console.WriteLine("RX: " + str.Trim());
}
}
catch (Exception err)
{
Console.WriteLine("ERR:" + err.Message);
}
Same code running on Windows 7 or on Linux arm 32 run without problem.
Someone can help me ?
Related
I need a help about my server. I have a program that sends a message over a socket with a TCP/IP connection and gets acknowledgment. My current problem is: I'm sending data to the machine I'm using for it to print. The machine confirms that it has received the data each time. But now it has to give feedback that it has printed the data after confirming that it has received the data. In the program I wrote, I cannot receive 2 messages in a row from the machine. What do I need to do to listen to multiple messages over Socket?
The code I use is below. Thanks for helps...
private void clientBaglanti(string ipAdres, int portNumarasi)
{
try
{
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = IPAddress.Parse(ipAdres); //ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, portNumarasi);
soket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
catch (Exception rt)
{
MessageBox.Show(rt.Message);
}
string sonMesaj;
sonMesaj = gonderilenText.ToCharArray().Aggregate("", (sonuc, c) => sonuc += ((!string.IsNullOrEmpty(sonuc) && (sonuc.Length + 1) % 3 == 0) ? " " : "") + c.ToString());
byte[] gonderilenVeri = sonMesaj.Split().Select(s => Convert.ToByte(s, 16)).ToArray();
byte b = checksumHesap(gonderilenVeri);
string txtChecksum = b.ToString("X2");
string toplamMesaj = sonMesaj + (" ") + txtChecksum;
byte[] gonderilenSonVeri = toplamMesaj.Split().Select(s => Convert.ToByte(s, 16)).ToArray();
int byteGonderilen = soket.Send(gonderilenSonVeri);
string stringGidenVeri = BitConverter.ToString(gonderilenSonVeri);
lstVtMakineHaberlesme.Items.Add("Gönderilen: " + stringGidenVeri);
byte[] cevap = new byte[1024];
int ht = soket.Receive(cevap);
string stringGelenVeri = BitConverter.ToString(cevap, 0, ht);
lstVtMakineHaberlesme.Items.Add("Gelen: " + stringGelenVeri);
I have a problem communicating with a UDP device
public IPEndPoint sendEndPoint;
public void senderUdpClient(byte message_Type, byte Command_Class, byte command_code,int argument1, int argument2)
{
string serverIP = "192.168.2.11";
int sendPort = 40960;
int receivePort = 40963;
// Calcul CheckSum
// We know the message plus the checksum has length 12
var packedMessage2 = new byte[12];
var packedMessage_hex = new byte[12];
// We use the new Span feature
var span = new Span<byte>(packedMessage2);
// We can directly set the single bytes
span[0] = message_Type;
span[1] = Command_Class;
span[2] = command_code;
// The pack is <, so little endian. Note the use of Slice: first the position (3 or 7), then the length of the data (4 for int)
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(3, 4), argument1);
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(7, 4), argument2);
// The checksum
// The sum is modulo 255, because it is a single byte.
// the unchecked is normally useless because it is standard in C#, but we write it to make it clear
var sum = unchecked((byte)packedMessage2.Take(11).Sum(x => x));
// We set the sum
span[11] = sum;
// Without checksum
Console.WriteLine(string.Concat(packedMessage2.Take(11).Select(x => $#"\x{x:x2}")));
// With checksum
Console.WriteLine(string.Concat(packedMessage2.Select(x => $#"\x{x:x2}")));
Console.WriteLine(string.Concat(packedMessage2.Take(1).Select(x => $#"\x{x:x2}")));
UdpClient senderClient = new UdpClient();
sendEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), sendPort);
try
{
senderClient.Connect(this.sendEndPoint);
senderClient.Send(packedMessage2, packedMessage2.Length);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), receivePort);
Thread.Sleep(5000);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = senderClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
senderClient.Close();
MessageBox.Show("Message Sent");
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
Form1
ObjHundler.senderUdpClient(1, 1, 0x24, 0 , 0);
there I build my message and I send it via port 40960
and I got a response via port 40963
Wireshark
On wireshark I send the message and the equipment sends a response but the code crashes in this line
Byte[] receiveBytes = senderClient.Receive(ref RemoteIpEndPoint);
Without filling in the table and without displaying any error message
Is there something missing from my code?
what could be the problem
Netstat -a cmd pour l'ip que j'utilise pour l'envoie 192.168.2.20
[CMD Netstat -a]
The solution =
you must create a UDPClient for reading.
It worked for me
public void senderUdpClient()
{
string serverIP = "192.168.2.11";
int sendPort = 40960;
int receivePort = 40963;
UdpClient senderClient = new UdpClient();
sendEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), sendPort);
try
{
senderClient.Connect(this.sendEndPoint);
senderClient.Send(packedMessage2, packedMessage2.Length);
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(receivePort);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
//string returnData = Encoding.ASCII.GetString(receiveBytes);
senderClient.Close();
MessageBox.Show("Message Sent");
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
I have a .NET application that was using TOR successfully on TOR. After updating the TOR to the version 6.5.2. I am not being able to refresh my TOR IP. Here is the code that I am currently using:
Socket server = null;
try
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9151);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Connect(ip);
// Please be sure that you have executed the part with the creation of an authentication hash, described in my article!
server.Send(Encoding.ASCII.GetBytes("AUTHENTICATE \"password\"" + Environment.NewLine));
byte[] data = new byte[1024];
int receivedDataLength = server.Receive(data);
string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
server.Send(Encoding.ASCII.GetBytes("SIGNAL NEWNYM" + Environment.NewLine));
data = new byte[1024];
receivedDataLength = server.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
if (!stringData.Contains("250"))
{
Console.WriteLine("Unable to signal new user to server.");
server.Shutdown(SocketShutdown.Both);
server.Close();
}
}
finally
{
server.Close();
}
When it gets to the line
receivedDataLength = server.Receive(data);
The application breaks with the message System.Net.Sockets.SocketException: 'An established connection was aborted by the software in your host machine'
Someone has any idea of what is going on? Or any tips for finding what is the problem?
Thanks in advance
Is it possible, to send a broadcast for searching a server application, if i don't know the port on which the server is running? Or do i have to check every port?
To send a simple broadcast, i found the following code at the internet:
Server
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Console.Write("Running server..." + Environment.NewLine);
server.Bind(new IPEndPoint(IPAddress.Any, 48000));
while (true)
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
byte[] buffer = new byte[1000];
server.ReceiveFrom(buffer, ref tempRemoteEP);
Console.Write("Server got '" + buffer[0] + "' from " + tempRemoteEP.ToString() + Environment.NewLine);
Console.Write("Sending '2' to " + tempRemoteEP.ToString() +
Environment.NewLine);
server.SendTo(new byte[] { 2 },
tempRemoteEP);
}
Client
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, 48000);
//Allow sending broadcast messages
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
//Send message to everyone
client.SendTo(new byte[] { 1 }, AllEndPoint);
Console.Write("Client send '1' to " + AllEndPoint.ToString() +
Environment.NewLine);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
byte[] buffer = new byte[1000];
string serverIp;
try
{
//Recieve from server. Don't wait more than 3000 milliseconds.
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 3000);
client.ReceiveFrom(buffer, ref tempRemoteEP);
Console.Write("Client got '" + buffer[0] + "' from " +
tempRemoteEP.ToString() + Environment.NewLine);
//Get server IP (ugly)
serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
}
catch
{
//Timout. No server answered.
serverIp = "?";
}
Console.Write("ServerIp: " + serverIp + Environment.NewLine);
Console.ReadLine();
But I don't know, wehter my server use port 48000.
To send a broadcast:
var port = 123;
var udp = new UdpClient();
var data = new byte[] { 1, 2, 3 };
udp.Send(data, data.Length, new IPEndPoint(IPAddress.Any, port));
If you don't know the port, you have to try all ports, which I do not recommend, since you're spamming the network.
What are you trying to do?
I can not send data stunserver remote computer using the two. Data comes from local computers, but data on remote computers is not going to come.
I'm using my program, stunserver
public void run()
{
UpdateText("Now Listening..");
remoteSender = new IPEndPoint(IPAddress.Any, 0);
tempRemoteEP = (EndPoint)remoteSender;
byte[] packet = new byte[1024];
while (true)
{
if (socket.Available > 0)
{
this.nbBytesRx = socket.ReceiveFrom(packet, ref tempRemoteEP);
nbPackets++;
seqNo = BitConverter.ToInt16(packet, 0);
UpdateText(nbPackets.ToString() + ":" + seqNo.ToString() + " / ");
}
}
}
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Any, 0));
string localEP = socket.LocalEndPoint.ToString();
string publicEP = "";
string netType = "";
STUN_Result result = STUN_Client.Query("stunserver.org", 3478, socket);
netType = result.NetType.ToString();
if (result.NetType != STUN_NetType.UdpBlocked)
{
publicEP = result.PublicEndPoint.ToString();
}
else
{
publicEP = "";
}
UpdateText("Local EP:" + localEP);
UpdateText("Public EP:" + publicEP);
ThreadStart startMethod = new ThreadStart(this.run);
thread = new Thread(startMethod);
thread.Start();
I am working on the same problem, and using the same library.
Did you check if you get your endpoint? I found our that pointed server wasn`t online. So I made a List of servers to go throught.
My method to get public EP:
public static IPEndPoint GetMyPublicEP() {
// Create new socket for STUN client.
Socket _socket = new Socket
(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_socket.Bind(new IPEndPoint(IPAddress.Any, 0));
List<string> _stunServers = new List<string> { // список стан серверов для проверки своей ендпоинт, не все работают
"stun.l.google.com:19302",
"stun1.l.google.com:19302",
"stun2.l.google.com:19302",
"stun3.l.google.com:19302",
"stun4.l.google.com:19302",
"stun01.sipphone.com",
"stun.ekiga.net",
"stun.fwdnet.net",
"stun.ideasip.com",
"stun.iptel.org",
"stun.rixtelecom.se",
"stun.schlund.de",
"stunserver.org",
"stun.softjoys.com",
"stun.voiparound.com",
"stun.voipbuster.com",
"stun.voipstunt.com",
"stun.voxgratia.org",
"stun.xten.com"
};
foreach (string server in _stunServers)
{
try
{
STUN_Result result = STUN_Client.Query(server, 3478, _socket);
IPEndPoint myPublicEPStun = result.PublicEndPoint;
if (myPublicEPStun != null)
{
_myPublicEPStun = myPublicEPStun;
break;
}
}
catch (Exception E)
{
Console.WriteLine("Якась необ`ясніма магія трапилась");
}
}
return _myPublicEPStun;
}
I had the same problem... i solved it disabling Windows Firewall. It was blocking all the traffic.