473,385 Members | 1,582 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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
Jul 18 '05 #1
11 10025
Nick Keighley:
is there a known problem with getting a Python based socket program to
communicate with a C based socket program?


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
Jul 18 '05 #2
Nick Keighley wrote:
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.


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

Jul 18 '05 #3
Eric Brunel <er*********@pragmadev.N0SP4M.com> wrote in message news:<bk**********@news-reader1.wanadoo.fr>...
Nick Keighley wrote:

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.


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

Can you post an example of your code?


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_PROTOCOL = 0
PORT = 8702

sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM,
DEFAULT_PROTOCOL)
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.sendall (receivedData)
newSocket.close()
print "disconnected from", address
finally:
sock.close ()
---------------------------------------------------------------------
C echo client (includes omitted)
-------------------------------
#define DEFAULT_PROTOCOL 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_PROTOCOL);
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_addr, 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
Jul 18 '05 #4
Eric Brunel <er*********@pragmadev.N0SP4M.com> wrote in message news:<bk**********@news-reader1.wanadoo.fr>...
Nick Keighley wrote:

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.


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

Can you post an example of your code?


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_PROTOCOL = 0
PORT = 8702

sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM,
DEFAULT_PROTOCOL)
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.sendall (receivedData)
newSocket.close()
print "disconnected from", address
finally:
sock.close ()
---------------------------------------------------------------------
C echo client (includes omitted)
-------------------------------
#define DEFAULT_PROTOCOL 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_PROTOCOL);
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_addr, 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
Jul 18 '05 #5
Nick Keighley:
sin.sin_port = PORT;


"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."
http://www.cs.rpi.edu/courses/sysprog/sockets/sock.html

--
René Pijlman
Jul 18 '05 #6
Nick Keighley:
sin.sin_port = PORT;


"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."
http://www.cs.rpi.edu/courses/sysprog/sockets/sock.html

--
René Pijlman
Jul 18 '05 #7
Eric Brunel <er*********@pragmadev.N0SP4M.com> wrote in message news:<bk**********@news-reader1.wanadoo.fr>...
Nick Keighley wrote:
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.


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

Can you post an example of your code?


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
Jul 18 '05 #8
Eric Brunel <er*********@pragmadev.N0SP4M.com> wrote in message news:<bk**********@news-reader1.wanadoo.fr>...
Nick Keighley wrote:
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.


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

Can you post an example of your code?


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
Jul 18 '05 #9
Nick Keighley wrote:
Eric Brunel <er*********@pragmadev.N0SP4M.com> wrote in message news:<bk**********@news-reader1.wanadoo.fr>...
Nick Keighley wrote:


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.


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

Can you post an example of your code?

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_PROTOCOL = 0
PORT = 8702

sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM,
DEFAULT_PROTOCOL)
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.sendall (receivedData)
newSocket.close()
print "disconnected from", address
finally:
sock.close ()
---------------------------------------------------------------------
C echo client (includes omitted)
-------------------------------
#define DEFAULT_PROTOCOL 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_PROTOCOL);
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_addr, 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;
}
------------------------------------------------------------------------------


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

Jul 18 '05 #10
Rene Pijlman <re********************@my.address.is.invalid> wrote in message news:<6f********************************@4ax.com>. ..
http://www.cs.rpi.edu/courses/sysprog/sockets/sock.html


looks handy!
Jul 18 '05 #11
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.However my client gives error "10061.connection
refused".Will send you the code of both server side and client side.:
server side:
------------
#include<stdio.h>
#include<winsock2.h>
#include <windows.h>

SOCKET recvSock,WinSocket,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(RecdBuffer,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_addr.S_un.S_addr = htonl(INADDR_ANY);
Acceptor.sin_family = AF_INET;
Acceptor.sin_port = 9999;

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

listen(WinSocket,1);
error = GetLastError();
if(error)
{
return 0;
}
recvSock = accept((SOCKET)WinSocket,(SOCKADDR
*)&Acceptor,&sizeofaddr);

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(WinSocket);
closesocket(recvSock);
}

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(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'socket not creadted'
try:
s.connect(("130.10.5.38", 9999))
except socket.error,msg:
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.
ni***********@marconi.com (Nick Keighley) wrote in message news:<8a*************************@posting.google.c om>...
Eric Brunel <er*********@pragmadev.N0SP4M.com> wrote in message news:<bk**********@news-reader1.wanadoo.fr>...
Nick Keighley wrote:
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.


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

Can you post an example of your code?


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!

Jul 18 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Josh | last post by:
I've been trying to get Tix running with Python on Windows. Since there is no binary distributions of Tix for Windows, it seems the easiest way to install Tix is through IDiscovery's IDEStudio 1.9...
699
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro...
11
by: Maxim Khesin | last post by:
Hi, being recently introduced to the joys of programming in a powerful dynamic language (go snake!) I periodically rethink which parts of C++ I still miss. One thing I really enjoy is the generics...
0
by: Heiko Wundram | last post by:
Hi all, esp. list admins! Why is it that I always get bounces saying my mails have suspicious headers lately when I post to python-list? This only happens when I reply to myself (as I just did,...
6
by: Gonzalo Monzón | last post by:
Hi all! I have been translating some Python custom C extension code into Python, as I need these modules to be portable and run on a PocketPC without the need of compile (for the purpose its a...
1
by: yichun.wei | last post by:
Perl has the ability to do the following: print <<EOF; ...reams of text goes here... EOF Is there a Python equivalent of the above Perl code? This thread has previous discussion on the...
7
by: sturlamolden | last post by:
On Windows, the standard Python 2.4 distro is compiled with Microsoft Visual C++ 2003 and is shipped with msvcr71.dll as a part of the binary installer. That is ok, as those who has a license for...
24
by: Mark | last post by:
Hi, I'm new to python and looking for a better idiom to use for the manner I have been organising my python scripts. I've googled all over the place about this but found absolutely nothing. I'm...
4
by: R Wood | last post by:
Greetings - A recent Perl experiment hasn't turned out so well, which has piqued my interest in Python. The project is this: take a Vcard file exported from Apple's Addressbook and use a...
23
by: Python Maniac | last post by:
I am new to Python however I would like some feedback from those who know more about Python than I do at this time. def scrambleLine(line): s = '' for c in line: s += chr(ord(c) | 0x80)...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.