1

I cannot find any example or a tutorial on how to send data from C# to python.

in my application, C# is supposed to keep reading data from a hardware and send it to python to be processed. i have tried to create a basic server on python and a basic client on C# and i was never able to establish connection between the client and the server with the following output from C# No connection could be made because the target machine actively refused it. i tested my python server on a python client and i was able to establish connection just fine.

how do i send data from C# to python correctly using sockets? is there any available tutorial on example i can follow? is there something wrong with my code? here it is:

Python Server code:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)

while True:
    clientsocket, address = s.accept()
    print(f"Connection from {address} has been established!")
    clientsocket.send(bytes("Welcome to the server!", "utf-8"))
    clientsocket.close()

C# Client Code:

 static void ExecuteClient()
        {

            try
            {

                IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ipAddr = ipHost.AddressList[0];
                IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 1234);

                Socket sender = new Socket(ipAddr.AddressFamily,
                           SocketType.Stream, ProtocolType.Tcp);

                try
                {
                    sender.Connect(localEndPoint);

                    Console.WriteLine("Socket connected to -> {0} ",
                                  sender.RemoteEndPoint.ToString());

                    byte[] messageReceived = new byte[1024];

                    int byteRecv = sender.Receive(messageReceived);
                    Console.WriteLine("Message from Server -> {0}",
                          Encoding.ASCII.GetString(messageReceived, 0, byteRecv));

                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }

                // Manage of Socket's Exceptions 
                catch (ArgumentNullException ane)
                {

                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }

                catch (SocketException se)
                {

                    Console.WriteLine("SocketException : {0}", se.ToString());
                }

                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
            }

            catch (Exception e)
            {

                Console.WriteLine(e.ToString());
            }
        }
4
  • The python code binds to socket.gethostname(). Documentation says: If you use a hostname in the host portion of IPv4/v6 socket address, the program may show a nondeterministic behavior, as Python uses the first address returned from the DNS resolution. The socket address will be resolved differently into an actual IPv4/v6 address, depending on the results from DNS resolution and/or the host configuration. For deterministic behavior use a numeric address in host portion. Commented Apr 1, 2020 at 20:30
  • And actively refused it means the specified port on target is listening but did not welcome you. Python has received, but did not like your TCP/IP packet. Commented Apr 1, 2020 at 20:33
  • python client replied with the same message when i tried to run it when the python server was closed. maybe im using the wrong protocol? i will test your first comment too Commented Apr 1, 2020 at 21:15
  • Sorry. You're right. It means the network card is reached but no one is listening to the endpoint in the IP packet on the server. Did you try the first one? I hope it helps. Commented Apr 1, 2020 at 22:56

1 Answer 1

2

I know this question is old, but incase some else stumbles here in their internet searching.

I just started down the road of learning Python and I'm working on a similar situation with my Raspberry Pi (SERVER) and Windows PC (CLIENT).

The problem is you're making a call to get the hostname on each machine. This is will obviously be different. Your client needs to connect to the address of the server. Your client code is trying to connect to the machine it's running and that connection is being refused. The server is never contacted.

I made the following changes and was able to establish a connection.

Python Server code:

s.bind(("", 1234))

C# Client Code:

//IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
//IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("[SERVER IP]"), 1234);

Server Console Response:

Connection from ('[CLIENT IP]', 52074) has been established!   

Client Console Response:

Socket connected to -> [::ffff:[SERVER IP]]:1234 
Message from Server -> Welcome to the server!
                                                                                    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.