Python <-> C via sockets

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Nick Keighley

    Python <-> C via sockets

    I'm probably missing something rather obvious, but is there a known
    problem with getting a Python based socket program to communicate with
    a C based socket program? A simple echo server written in Python
    (the example from Python in a Nutshell actually) will happily talk
    to a Python based client. If a C based client is substitued the connection
    is refused (or so the C client reports). The C client will talk to
    a C server.


    --
    Nick Keighley
  • Rene Pijlman

    #2
    Re: Python &lt;-&gt; C via sockets

    Nick Keighley:[color=blue]
    >is there a known problem with getting a Python based socket program to
    >communicate with a C based socket program?[/color]

    No. Client and server are completely independent and can be implemented in
    any language.

    They must speak the same application level protocol of course, on top of
    TCP/IP.

    --
    René Pijlman

    Comment

    • Eric Brunel

      #3
      Re: Python &lt;-&gt; C via sockets

      Nick Keighley wrote:[color=blue]
      > I'm probably missing something rather obvious, but is there a known
      > problem with getting a Python based socket program to communicate with
      > a C based socket program? A simple echo server written in Python
      > (the example from Python in a Nutshell actually) will happily talk
      > to a Python based client. If a C based client is substitued the connection
      > is refused (or so the C client reports). The C client will talk to
      > a C server.[/color]

      Communications between C and Python via sockets definetly work: we do that every
      day (no kidding ;-)

      Can you post an example of your code?
      --
      - Eric Brunel <eric dot brunel at pragmadev dot com> -
      PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com

      Comment

      • Nick Keighley

        #4
        Re: Python &lt;-&gt; C via sockets

        Eric Brunel <eric.brunel@pr agmadev.N0SP4M. com> wrote in message news:<bkroq8$8u d$1@news-reader1.wanadoo .fr>...[color=blue]
        > Nick Keighley wrote:[/color]
        [color=blue][color=green]
        > > I'm probably missing something rather obvious, but is there a known
        > > problem with getting a Python based socket program to communicate with
        > > a C based socket program? A simple echo server written in Python
        > > (the example from Python in a Nutshell actually) will happily talk
        > > to a Python based client. If a C based client is substitued the connection
        > > is refused (or so the C client reports). The C client will talk to
        > > a C server.[/color]
        >
        > Communications between C and Python via sockets definetly work: we do that
        > every day (no kidding ;-)
        >
        > Can you post an example of your code?[/color]

        well I assumed sockets actually worked I was guessing the slight
        differences in the interfaces caused me to set the two ends up
        slightly
        differently.

        Python Echo Server
        ------------------
        import socket

        DEFAULT_PROTOCO L = 0
        PORT = 8702

        sock = socket.socket (socket.AF_INET , socket.SOCK_STR EAM,
        DEFAULT_PROTOCO L)
        sock.bind (('', PORT))
        sock.listen (5)

        # wait for a connection
        try:
        while True:
        newSocket, address = sock.accept ()
        print "connected from", address
        while True:
        receivedData = newSocket.recv (8192)
        if not receivedData:
        break
        print "received: ", receivedData
        newSocket.senda ll (receivedData)
        newSocket.close ()
        print "disconnect ed from", address
        finally:
        sock.close ()
        ---------------------------------------------------------------------
        C echo client (includes omitted)
        -------------------------------
        #define DEFAULT_PROTOCO L 0
        #define PORT 8702
        #define HOST "localhost"
        /* #define HOST "127.0.0.1" */
        /* #define HOST "cmopc018" */
        #define TYPE SOCK_STREAM


        int main (void)
        {
        struct hostent *phe;
        struct sockaddr_in sin;
        int s;

        s = socket (PF_INET, TYPE, DEFAULT_PROTOCO L);
        if (s < 0)
        raise_report (LEVEL_FATAL, "tiny_echo" , "can't create socket:
        %s", strerror (errno));


        /*
        * connect to the socket
        */

        memset (&sin, 0, sizeof sin);
        sin.sin_family = AF_INET;
        sin.sin_port = PORT;
        if ((phe = gethostbyname (HOST)))
        {
        memcpy (&sin.sin_add r, phe->h_addr_list[0], phe->h_length);
        raise_report (LEVEL_INFO, "tiny_echo" , "addr is %X",
        sin.sin_addr);
        }
        else
        if ((sin.sin_addr. s_addr = inet_addr (HOST)) == INADDR_NONE)
        raise_report (LEVEL_FATAL, "tiny_echo" , "can't get \"%s\"
        host entry", HOST);

        if (connect (s, (struct sockaddr *)&sin, sizeof sin) < 0)
        raise_report (LEVEL_FATAL, "tiny_echo" , "can't connect to
        %s.%d: %s", HOST, sin.sin_port, strerror (errno));

        raise_report (LEVEL_INFO, "tiny_echo" , "CONNECTED" );

        return 0;
        }
        ------------------------------------------------------------------------------


        --
        Nick Keighley

        Comment

        • Nick Keighley

          #5
          Re: Python &lt;-&gt; C via sockets

          Eric Brunel <eric.brunel@pr agmadev.N0SP4M. com> wrote in message news:<bkroq8$8u d$1@news-reader1.wanadoo .fr>...[color=blue]
          > Nick Keighley wrote:[/color]
          [color=blue][color=green]
          > > I'm probably missing something rather obvious, but is there a known
          > > problem with getting a Python based socket program to communicate with
          > > a C based socket program? A simple echo server written in Python
          > > (the example from Python in a Nutshell actually) will happily talk
          > > to a Python based client. If a C based client is substitued the connection
          > > is refused (or so the C client reports). The C client will talk to
          > > a C server.[/color]
          >
          > Communications between C and Python via sockets definetly work: we do that
          > every day (no kidding ;-)
          >
          > Can you post an example of your code?[/color]

          well I assumed sockets actually worked I was guessing the slight
          differences in the interfaces caused me to set the two ends up
          slightly
          differently.

          Python Echo Server
          ------------------
          import socket

          DEFAULT_PROTOCO L = 0
          PORT = 8702

          sock = socket.socket (socket.AF_INET , socket.SOCK_STR EAM,
          DEFAULT_PROTOCO L)
          sock.bind (('', PORT))
          sock.listen (5)

          # wait for a connection
          try:
          while True:
          newSocket, address = sock.accept ()
          print "connected from", address
          while True:
          receivedData = newSocket.recv (8192)
          if not receivedData:
          break
          print "received: ", receivedData
          newSocket.senda ll (receivedData)
          newSocket.close ()
          print "disconnect ed from", address
          finally:
          sock.close ()
          ---------------------------------------------------------------------
          C echo client (includes omitted)
          -------------------------------
          #define DEFAULT_PROTOCO L 0
          #define PORT 8702
          #define HOST "localhost"
          /* #define HOST "127.0.0.1" */
          /* #define HOST "cmopc018" */
          #define TYPE SOCK_STREAM


          int main (void)
          {
          struct hostent *phe;
          struct sockaddr_in sin;
          int s;

          s = socket (PF_INET, TYPE, DEFAULT_PROTOCO L);
          if (s < 0)
          raise_report (LEVEL_FATAL, "tiny_echo" , "can't create socket:
          %s", strerror (errno));


          /*
          * connect to the socket
          */

          memset (&sin, 0, sizeof sin);
          sin.sin_family = AF_INET;
          sin.sin_port = PORT;
          if ((phe = gethostbyname (HOST)))
          {
          memcpy (&sin.sin_add r, phe->h_addr_list[0], phe->h_length);
          raise_report (LEVEL_INFO, "tiny_echo" , "addr is %X",
          sin.sin_addr);
          }
          else
          if ((sin.sin_addr. s_addr = inet_addr (HOST)) == INADDR_NONE)
          raise_report (LEVEL_FATAL, "tiny_echo" , "can't get \"%s\"
          host entry", HOST);

          if (connect (s, (struct sockaddr *)&sin, sizeof sin) < 0)
          raise_report (LEVEL_FATAL, "tiny_echo" , "can't connect to
          %s.%d: %s", HOST, sin.sin_port, strerror (errno));

          raise_report (LEVEL_INFO, "tiny_echo" , "CONNECTED" );

          return 0;
          }
          ------------------------------------------------------------------------------


          --
          Nick Keighley

          Comment

          • Rene Pijlman

            #6
            Re: Python &lt;-&gt; C via sockets

            Nick Keighley:[color=blue]
            > sin.sin_port = PORT;[/color]

            "serv_addr.sin_ port = htons(portno);

            The second field of serv_addr is unsigned short sin_port , which contain
            the port number. However, instead of simply copying the port number to
            this field, it is necessary to convert this to network byte order using
            the function htons() which converts a port number in host byte order to a
            port number in network byte order."


            --
            René Pijlman

            Comment

            • Rene Pijlman

              #7
              Re: Python &lt;-&gt; C via sockets

              Nick Keighley:[color=blue]
              > sin.sin_port = PORT;[/color]

              "serv_addr.sin_ port = htons(portno);

              The second field of serv_addr is unsigned short sin_port , which contain
              the port number. However, instead of simply copying the port number to
              this field, it is necessary to convert this to network byte order using
              the function htons() which converts a port number in host byte order to a
              port number in network byte order."


              --
              René Pijlman

              Comment

              • Nick Keighley

                #8
                Re: Python &lt;-&gt; C via sockets

                Eric Brunel <eric.brunel@pr agmadev.N0SP4M. com> wrote in message news:<bkroq8$8u d$1@news-reader1.wanadoo .fr>...[color=blue]
                > Nick Keighley wrote:[color=green]
                > > I'm probably missing something rather obvious, but is there a known
                > > problem with getting a Python based socket program to communicate with
                > > a C based socket program? A simple echo server written in Python
                > > (the example from Python in a Nutshell actually) will happily talk
                > > to a Python based client. If a C based client is substitued the connection
                > > is refused (or so the C client reports). The C client will talk to
                > > a C server.[/color]
                >
                > Communications between C and Python via sockets definetly work: we do that
                > every day (no kidding ;-)
                >
                > Can you post an example of your code?[/color]

                by the time you read this the posted code may have appeared.
                A call to htons() (convert unsigned short to network byte order)
                was ommitted on the C side.

                this line:-
                sin.sin_port = PORT;

                should read:-
                sin.sin_port = htons(PORT);


                thanks!

                --
                Nick Keighley

                Comment

                • Nick Keighley

                  #9
                  Re: Python &lt;-&gt; C via sockets

                  Eric Brunel <eric.brunel@pr agmadev.N0SP4M. com> wrote in message news:<bkroq8$8u d$1@news-reader1.wanadoo .fr>...[color=blue]
                  > Nick Keighley wrote:[color=green]
                  > > I'm probably missing something rather obvious, but is there a known
                  > > problem with getting a Python based socket program to communicate with
                  > > a C based socket program? A simple echo server written in Python
                  > > (the example from Python in a Nutshell actually) will happily talk
                  > > to a Python based client. If a C based client is substitued the connection
                  > > is refused (or so the C client reports). The C client will talk to
                  > > a C server.[/color]
                  >
                  > Communications between C and Python via sockets definetly work: we do that
                  > every day (no kidding ;-)
                  >
                  > Can you post an example of your code?[/color]

                  by the time you read this the posted code may have appeared.
                  A call to htons() (convert unsigned short to network byte order)
                  was ommitted on the C side.

                  this line:-
                  sin.sin_port = PORT;

                  should read:-
                  sin.sin_port = htons(PORT);


                  thanks!

                  --
                  Nick Keighley

                  Comment

                  • Eric Brunel

                    #10
                    Re: Python &lt;-&gt; C via sockets

                    Nick Keighley wrote:[color=blue]
                    > Eric Brunel <eric.brunel@pr agmadev.N0SP4M. com> wrote in message news:<bkroq8$8u d$1@news-reader1.wanadoo .fr>...
                    >[color=green]
                    >>Nick Keighley wrote:[/color]
                    >
                    >[color=green][color=darkred]
                    >>>I'm probably missing something rather obvious, but is there a known
                    >>>problem with getting a Python based socket program to communicate with
                    >>>a C based socket program? A simple echo server written in Python
                    >>>(the example from Python in a Nutshell actually) will happily talk
                    >>>to a Python based client. If a C based client is substitued the connection
                    >>>is refused (or so the C client reports). The C client will talk to
                    >>>a C server.[/color]
                    >>
                    >>Communication s between C and Python via sockets definetly work: we do that
                    >>every day (no kidding ;-)
                    >>
                    >>Can you post an example of your code?[/color]
                    >
                    >
                    > well I assumed sockets actually worked I was guessing the slight
                    > differences in the interfaces caused me to set the two ends up
                    > slightly
                    > differently.
                    >
                    > Python Echo Server
                    > ------------------
                    > import socket
                    >
                    > DEFAULT_PROTOCO L = 0
                    > PORT = 8702
                    >
                    > sock = socket.socket (socket.AF_INET , socket.SOCK_STR EAM,
                    > DEFAULT_PROTOCO L)
                    > sock.bind (('', PORT))
                    > sock.listen (5)
                    >
                    > # wait for a connection
                    > try:
                    > while True:
                    > newSocket, address = sock.accept ()
                    > print "connected from", address
                    > while True:
                    > receivedData = newSocket.recv (8192)
                    > if not receivedData:
                    > break
                    > print "received: ", receivedData
                    > newSocket.senda ll (receivedData)
                    > newSocket.close ()
                    > print "disconnect ed from", address
                    > finally:
                    > sock.close ()
                    > ---------------------------------------------------------------------
                    > C echo client (includes omitted)
                    > -------------------------------
                    > #define DEFAULT_PROTOCO L 0
                    > #define PORT 8702
                    > #define HOST "localhost"
                    > /* #define HOST "127.0.0.1" */
                    > /* #define HOST "cmopc018" */
                    > #define TYPE SOCK_STREAM
                    >
                    >
                    > int main (void)
                    > {
                    > struct hostent *phe;
                    > struct sockaddr_in sin;
                    > int s;
                    >
                    > s = socket (PF_INET, TYPE, DEFAULT_PROTOCO L);
                    > if (s < 0)
                    > raise_report (LEVEL_FATAL, "tiny_echo" , "can't create socket:
                    > %s", strerror (errno));
                    >
                    >
                    > /*
                    > * connect to the socket
                    > */
                    >
                    > memset (&sin, 0, sizeof sin);
                    > sin.sin_family = AF_INET;
                    > sin.sin_port = PORT;
                    > if ((phe = gethostbyname (HOST)))
                    > {
                    > memcpy (&sin.sin_add r, phe->h_addr_list[0], phe->h_length);
                    > raise_report (LEVEL_INFO, "tiny_echo" , "addr is %X",
                    > sin.sin_addr);
                    > }
                    > else
                    > if ((sin.sin_addr. s_addr = inet_addr (HOST)) == INADDR_NONE)
                    > raise_report (LEVEL_FATAL, "tiny_echo" , "can't get \"%s\"
                    > host entry", HOST);
                    >
                    > if (connect (s, (struct sockaddr *)&sin, sizeof sin) < 0)
                    > raise_report (LEVEL_FATAL, "tiny_echo" , "can't connect to
                    > %s.%d: %s", HOST, sin.sin_port, strerror (errno));
                    >
                    > raise_report (LEVEL_INFO, "tiny_echo" , "CONNECTED" );
                    >
                    > return 0;
                    > }
                    > ------------------------------------------------------------------------------[/color]

                    After adding the missing htons and replacing the raise_report's by printf's,
                    works like a charm here (Linux Mandrake 8.0 with Python 2.1).

                    What is exactly the error you get?
                    --
                    - Eric Brunel <eric dot brunel at pragmadev dot com> -
                    PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com

                    Comment

                    • Nick Keighley

                      #11
                      Re: Python &lt;-&gt; C via sockets

                      Rene Pijlman <reply.in.the.n ewsgroup@my.add ress.is.invalid > wrote in message news:<6f83nv47k 9m7qm4pace4lvfd faqmof47ei@4ax. com>...
                      [color=blue]
                      > http://www.cs.rpi.edu/courses/sysprog/sockets/sock.html[/color]

                      looks handy!

                      Comment

                      • anuradha.k.r@sify.com

                        #12
                        Re: Python &lt;-&gt; C via sockets

                        hi,
                        I 've already posted a message to this group but i think You guys can
                        provide a solution faster.My problem is similar ,my client side
                        (written in python) is not able to connect to the server side
                        (written in C) in the same machine.
                        my server side works perfectly fine and it waits for a connection to b
                        established.How ever my client gives error "10061.connecti on
                        refused".Will send you the code of both server side and client side.:


                        server side:
                        ------------
                        #include<stdio. h>
                        #include<winsoc k2.h>
                        #include <windows.h>

                        SOCKET recvSock,WinSoc ket,slisten;
                        WSADATA WSAData;
                        SOCKADDR_IN Acceptor;
                        SOCKADDR_IN Connector;
                        int TypeOfCon;
                        int Initialise();
                        SOCKET ListenSocket();
                        int RecvBuff(BYTE * RecdBuffer,int size);
                        void Close();
                        unsigned char * RecdBuffer;

                        int main()
                        {
                        int flag;
                        flag = Initialise();
                        slisten= ListenSocket();
                        flag = RecvBuff(RecdBu ffer,20);
                        Close();
                        return 1;
                        }

                        int Initialise()
                        {
                        WSAStartup (MAKEWORD(1,1), &WSAData);
                        WinSocket = socket (AF_INET/*2*/, SOCK_STREAM/*1*/, 0);
                        recvSock = socket (AF_INET/*2*/, SOCK_STREAM/*1*/, 0);
                        return 1;
                        }

                        SOCKET ListenSocket()
                        {
                        int error;
                        int sizeofaddr;
                        sizeofaddr = sizeof(Acceptor );

                        /*BOOL mcast ;
                        mcast= TRUE;*/

                        Acceptor.sin_ad dr.S_un.S_addr = htonl(INADDR_AN Y);
                        Acceptor.sin_fa mily = AF_INET;
                        Acceptor.sin_po rt = 9999;

                        bind(WinSocket, (const SOCKADDR *)&Acceptor,siz eof(Acceptor));
                        error = GetLastError();
                        if(error)
                        {
                        return 0;
                        }

                        listen(WinSocke t,1);
                        error = GetLastError();
                        if(error)
                        {
                        return 0;
                        }
                        recvSock = accept((SOCKET) WinSocket,(SOCK ADDR
                        *)&Acceptor,&si zeofaddr);

                        error = GetLastError();
                        if(error)
                        {
                        return 0;
                        }
                        return recvSock;

                        }

                        int RecvBuff(BYTE * Buffer,int size)
                        {
                        int amount,error;

                        amount = recv(recvSock,( char *)Buffer,size,0 );
                        error = GetLastError();
                        if(error)
                        {
                        return 0;
                        }
                        else
                        return 1;
                        }

                        void Close()
                        {
                        closesocket(Win Socket);
                        closesocket(rec vSock);
                        }

                        client side:
                        -------------

                        import socket

                        #HOST = '130.10.5.38' # The remote host
                        #PORT = 50007 # The same port as used by the server
                        try:
                        s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
                        except socket.error:
                        print 'socket not creadted'
                        try:
                        s.connect(("130 .10.5.38", 9999))
                        except socket.error,ms g:
                        print 'error in connect'

                        #s.send('Hello, world')
                        #data = s.recv(1024)
                        s.close()
                        #print 'Received', `data`

                        I'd gone thru the discussion above,so i guess probably the problem
                        with my code is also on the port address only.Pls help.
                        thanx,
                        AKR.


                        nick.keighley@m arconi.com (Nick Keighley) wrote in message news:<8ad2cfb3. 0309240628.dbbc a33@posting.goo gle.com>...[color=blue]
                        > Eric Brunel <eric.brunel@pr agmadev.N0SP4M. com> wrote in message news:<bkroq8$8u d$1@news-reader1.wanadoo .fr>...[color=green]
                        > > Nick Keighley wrote:[color=darkred]
                        > > > I'm probably missing something rather obvious, but is there a known
                        > > > problem with getting a Python based socket program to communicate with
                        > > > a C based socket program? A simple echo server written in Python
                        > > > (the example from Python in a Nutshell actually) will happily talk
                        > > > to a Python based client. If a C based client is substitued the connection
                        > > > is refused (or so the C client reports). The C client will talk to
                        > > > a C server.[/color]
                        > >
                        > > Communications between C and Python via sockets definetly work: we do that
                        > > every day (no kidding ;-)
                        > >
                        > > Can you post an example of your code?[/color]
                        >
                        > by the time you read this the posted code may have appeared.
                        > A call to htons() (convert unsigned short to network byte order)
                        > was ommitted on the C side.
                        >
                        > this line:-
                        > sin.sin_port = PORT;
                        >
                        > should read:-
                        > sin.sin_port = htons(PORT);
                        >
                        >
                        > thanks![/color]

                        Comment

                        Working...