Socket Programming tutorial

Friday, July 4, 2008

Generic Socket Programming tutorial

S.Prasanna
sprasanna199@gmail.com

This is a generic socket programming tutorial which mainly concentrates on how to communicate with two machines using TCP/IP and UDP/IP protocols irrespective of the programming language used to implement the server and client

I will list a simple Connection oriented (TCP) and Connectionless (UDP) Server and Client programs for all the four languages namely Python , Perl, C and Java. The TCP Server program is an iterative one which means it will process clients one by one. The communication between the TCP Server and the Client is a simple chat program. If the client quits, the current TCP connection between the server and the client gets disconnected and the server processes the next client and if the server decides to quit, that client gets disconnected and the server processes the next client.

The UDP Server program is very simple. The server recieves datagrams from many clients and prints them.

In all the programs , the Server process listens at port 5000 and I have used loopback address for the Server so that you can run the server and the client in different terminals in the same system. Besides you can use any of the four servers implemented in Python , Perl, C and Java with any of the four client programs implemented inthe four languages.In short you can use a Client program in Perl with a Server program in python , Server program in python with a Client progam in C , etc. Morever you can invoke the client program without any command line arguments since the client and the server are designed to communicate using the loopback address.

I will go from easy to difficult ( in terms of readability and lines of code ). i.e for example socket programming is simple and easy to understand in Python than in C or java.


1. Socket programming in Python

Connection oriented Server and Client program.

tcpserver.py and tcpclient.py

Connectionless Server and Client program.

udpserver.py and udpclient.py


2. Socket programming in Perl

Connection oriented Server and Client program.

tcpserver.pl and tcpclient.pl

Connectionless Server and Client program.

udpserver.pl and udpclient.pl


3. Socket programming in C

Connection oriented Server and Client program.

tcpserver.c and tcpclient.c

Connectionless Server and Client program.

udpserver.c and udpclient.c


4. Socket programming in Java

Connection oriented Server and Client program.

TCPServer.java and TCPClient.java

Connectionless Server and Client program.

UDPServer.java and UDPClient.java

I will list similar programs in as many languages in future. I could have explained about the details of sockets, how system calls like socket , bind, listen, etc works, but those should be explained from the perspectives different languages which is beyond the scope of this tutorial. In general these programs explain the fundamental concepts of socket programming irrespective of their implementation language.

Socket programming can be easily understood in interpreted languages like Perl and Python. Perl, especially is weapon for hackers. Dangerous scripts can be developed in minutes, in perl. For example spoofing source IP address can easliy be done in Perl but it requires some effort in C or in other languages. This small script shows how to spoof UDP source address.

Raw Sockets Programming (UDP Spoofing):

udpspoof.pl and udpserver.c

When you run the above simple script as client you can see the fake IP source address and the port the client used at the UDPServer. To execute the Perl script you need the Net::RawIP Module which can be downloaded here and also its documentation.

TCP/IP spoofing is a challenging task and involves a lot of calculation involving prediction of sequence numbers,etc but worth giving a try.

References:

1. Beej's guide to Network Programming

The highly rated Socket Programming tutorial in the Web. It explains all system calls used for socket programming in a clear way and also about Networking concepts in general.

2. UNIX Sockets for Newbies

Another Wonderful Socket programming tutorial.

3. Network Programming in Python

An excellent document on Python Socket programming.

4. UNIX Sockets FAQ

Answers to common questions asked by socket programmers.

5. Perl Socket Programming tutorial

Good introduction to Perl sockets.

6. http://pont.net/socket/index.html

A Collection of different Client-Server programs in C and Java.

207 comments:

«Oldest   ‹Older   1 – 200 of 207   Newer›   Newest»
FOF-ff said...

Thank you this helped so much!, i'm in the works of making an offline game , online, the game is called frets on fire, and its like "guitar hero" so for multi player i need it to send the score, do you know how to make the client send the score from one client to my server to another client? and vice versa?

Prasanna Seshadri said...

Thats a good question, I have done it in the past, having many clients and a server with clients exchanging messages through the server.

Watch out my blog, I will post that solution in a couple of days, which is pretty easy.

FOF-ff said...

thanks cant wait :)

FOF-ff said...

also im using java as the server, and pythong client(s)

Prasanna Seshadri said...

Sure, mine will be in python (both clients and server part), I am sure it will be very useful to you, its in testing stage right now, but will be done early this week.

Prasanna Seshadri said...

Hi,

Heres what you're looking for, I have written a tutorial on using asynchronous I/O using python sockets which will solve your problem.
http://www.prasannatech.net/2008/07/asynchronous-sock

Anonymous said...

I am new to socket programming and wanted to understand the communication of a client with a server of different technology. This article was useful. Thanks.

BTW..the link in your response to FOF-ff is incorrect. Heres the correct link
http://www.prasannatech.net/2008/07/asynchronous-socket-programming-select.html

Prasanna Seshadri said...

Glad that it was useful to you, I will change that link for sure.

Dileep said...

Hi,
I am new to socket programming. I am trying the code that you have given for client and server for windows. But the problem I am facing is there is no socket.h file in my system. Plase tell me how can I proceed in this situation

Thanks
Dileep Kumar

Prasanna Seshadri said...

Hi Dileep,

The socket code in C is mainly for Unix/Linux environments, however for making it work in windows, you may try Cygwin GCC compiler(www.cygwin.org).

Anonymous said...

Best client/server page I've run across over a long time of Googling.

Very good job.

Prasanna Seshadri said...

Thanks for saying so :)

Vince said...

Thank you Mr.Prasanna
I'm newbie for socket programming.
I'm so glad to found such good sample for TCP server and client. I was looking for it few days already but cant find satisfy one. Others are not work or too hard to debug. Thanks for your afford

Sincerely,
Vince

Prasanna Seshadri said...

Thanks Vince for saying so, glad that you found it useful.

kakesblog said...

hello sir,
sir I'm a newbie to socket programming. Can you suggest me some books or tutorials which will help me in understanding socket programming in C language for TCP sockets.That will be a great help .

Prasanna Seshadri said...

Hi,

If you are a newbie, the best thing you can do is to refer some of the online tutorials which I mentioned in the reference column, once you have a grasp of the fundamental concepts, the following books may be useful.

1. Java Network Programming, Third Edition by Elliotte Harold (Author), Elliotte Rusty Harold

If you are Java centric.

2. Unix Network Programming, Volume 1: The Sockets Networking API (3rd Edition) (Addison-Wesley Professional Computing Series) by W. Richard Stevens

If you interested in core socket programming in C.

You can get these from Amazon.

Stingers Destiny said...

Hi
Thanks for the programs. I am trying to use Java (Server) and Python (CLient) but somehow i cant get it to work with the message from Server to Client back.

The problem is the same when i reverse the CLient (to Java) and server (to Python)

Is it to with flush or something..??

Prasanna Seshadri said...

Hi,

Thanks a lot for pointing out, yes it may be a flush issue, I will ensure that I change the java IO stream to the right one to make it work.

Would fix that soon and let you know.

Sunny said...

Thanks this is great.
Do you have a version of this written for windows using c.
Thanks.

Sunny said...

Never mind. I was able to compile the code in windows by making a few changes.
First off I added #include WinSock2.h
Next Used memset instead of bzero and used closesocket instead of close.

I did all this easily but faced a issue of code not compiling in Visual Studio. I was getting some wierd linking errors....error LNK2001: unresolved external symbol __imp__WSAStartup and then I found this article (http://msdn.microsoft.com/en-us/library/ms737629(VS.85).aspx#) which tells how to fix it. Basically I had to link WS2_32.lib in the build environment. The link talks about how to do it.

Prasanna Seshadri said...

Hi,

Glad that you solved your issue, I had a tough time in the past trying to compile socket code in Windows, yes you need to link some libraries.

Because of some issues I faced similar to what you have been facing, I switched to Linux, you can always use Cygwin to run your socket code in Windows unless its a VC++ Project you are working on or use scripting languages to code sockets.

I am also considering to have one windows version to make this complete, not sure when will I be able to do it, probably when time permits.

Sunny said...

Hi,
Can you tell me how do I use recv to read data sent to my client from server. The server is sending ACK (1\r\n... when data from client is received by server) and then followed by a status message which is result of server doing some command calls.

I need a way to get ACK to validate data over the socket was received by server and then get the status message from the server on the client.

Thanks for your help.

Prasanna Seshadri said...

Hi,

I got your problem, first my question is are you trying to send an ACK to the client to acknowledge the client request, in case you are using tcp socket this is not needed since its a guaranteed transfer protocol in which case a reply from the server to a particular client means that it got the command status.

If you are still using ACK, then have recv() call, then check the recv string, if its ACK string wait for another recv to get the status, on the other hand if any of the recv() calls throws an exception "Connection reset by peer" when the server closes the connection with the client, then close the client socket and exit.

Let me know if this helps.

Look at my C socket code on how this is done, in windows also it would be the same.

Anonymous said...

Hi , I was looking for Async Tcp server in python..I guess the link http://www.prasannatech.net/2008/07/asynchronous-sock
is broken, could be please post the program, thanks a load

Prasanna Seshadri said...

Hi,

You can easily find that section, in the top left labels section, click on socket programming, you can find three articles, one on socket programming and the other were asynchronous socket programming in python, somehow posting link in the comment section doesn't work properly.

Anonymous said...

Hi Prasanna.

Please help me in finding out the server status through java programming

Prasanna Seshadri said...

Hi,

For more info on return codes in sockets in java, do refer the official Socket java class doc here.

http://java.sun.com/j2se/1.4.2/docs/api/java/net/Socket.html

Anonymous said...

thanks Prasanna for your kind reply

php application development said...

Nice post prasanna, keep it up dude!!!!

Prasanna Seshadri said...

Thanks a lot for saying so, Welcome.

Vasu said...

hi prasanna seshadri..This is vasu from hyderabad,india..I am doing a project on WEB APPLICATION SECURITY SCANNER.SO i need to do some socket programming to connect to remote WEB SERVER.
Can u please tell me in which language(java or c) the socket programming is efficient,robust and easy to implement.Waiting for ur reply..

Prasanna Seshadri said...

Hi Vasu,

For your application, the best language would be java, java has excellent built in modules to implement web server and some security APIs as well to design your web application scanner, do look at the book "Java Security" by Oreilly which may be useful for you.

Krishnamachchaari said...

Hi Prasanna,

I am a newbie to socket programming. I am trying to design a server that can store a customers name, password and balance. I thought of writing these in a separate txt file after strtok() for removing all the commas. But i think the program will be slow due to the operations it has to do. Is there any better way to do this?

Prasanna Seshadri said...

Hi,

It all depends on how many customers you are handling, if its large, then it would cause huge performance hit in retrieving a customer data if you write it this way, in which case you should use a light weight DB.

Another more way to solve this is to have individual text files for each customer identified by a unique ID derived from their name and other details (like SSN) and store it in the text file, doing this way would make it easy to retrieve the customer details from that file based on name/balance or other unique detail for that customer, also it you want to delete that customer's record, its just a matter of deleting that file alone.

aya ibrahim said...

hi,
I'm student in faculty of computers and information and I'm new in Socket programming in java
i have question,
how I can divide video on the client into packets and send packets to server
Really i need your respond,it is very important to me

Prasanna Seshadri said...

To send video to server, use an InputStream like BufferedInput Stream and fetch the video binary contents in a buffer and then transfer them to the server, do look at the java code I have used to transfer bytes through socket, if you have doubts, let me know.

Anonymous said...

Hi Prasanna

I am satya, I have one problem ,how can I send or receive numeric values to client/server. what is the function to send numeric values to server/client.

Prasanna Seshadri said...

Hi Satya,

The solution to transfer numeric values is quite simple, you just need to convert the numbers into string using functions like toString in java or str in python, in C there is an itoa function to do the same, you can always get the number back from string using the reverse function like atoi in C, int() in python, Integer.getInteger method in java.

Sunny said...

Hi Prasanna,
Please refer to my comment posted on November 10, 2008 4:13 PM and your reply.

So my client has a recv() call after the send and it always bring back 1/r/n (ACK). Then I do another recv() to get the message back from the server. On most of the scenarios this works perfect but in some cases the client gets nothing from the server because the server has not put the message on the socket. I am trying to fix this to get the message in second recv() call (since the first recv() call brings back ACK).

So I added a timeout to the recv() call as described in Beej's guide. This works fine but now the client always wait the timeout seconds before the reply is sent. So, if I set the timeout to be 4 seconds, I get a reply from my client exactly after 4 seconds. I was hoping to get the message back as soon as it was on socket.

I was reading something for non-blocking that would do this kind of thing but I am new to this and could not get much.

Do you have any recommendations. Here is the code I have without the timeout implemented in recv().

iResult = send(sock,send_data,strlen(send_data), 0);
if (iResult == SOCKET_ERROR)
{
closesocket(sock);
return RETURN_ERROR; //store transactions as offline transaction.
}

// read socket for ACK from Integrator
bytes_recieved = recv(sock,recv_data,SOCK_MAX_SEND_RECEIVE,0);
if(bytes_recieved == SOCKET_ERROR)
{
closesocket(sock);
return RETURN_ERROR; //store transactions as offline transaction.
}


if(strcmp(recv_data,"1\\r\\n")) //ACK received
{
bytes_recieved = recv(sock,recv_data,SOCK_MAX_SEND_RECEIVE,0); //second recv()
if(bytes_recieved == SOCKET_ERROR)
{
closesocket(sock);
return RETURN_ERROR; //store transactions as offline transaction.
}
else if (bytes_recieved >0)
{
//print the message out
}
}

Sunny said...

Do you have an example of non-blocking sockets and recv(call working together?

Thanks.

Sunny said...

Hi again,
I tired the following as described by Microsoft (MSDN) but I get a crash when recv() is called for second time in the loop. I guess there is no data on the socket to receive during the second call but I am not sure how to handle it.

// Receive until the peer closes the connection
do {

iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());

} while( iResult > 0 );

Prasanna Seshadri said...

Hi,

You need to handle recv for exceptions as well, I had a writing on non-blocking sockets in python here, where I handled recv call and the possible exceptions it can throw, do look at it here

http://www.prasannatech.net/2008/08/non-blocking-sockets.html

I think the code for C is similar, if you hit the walls, let me know.

Note that the behavior of recv exception is different in Unix and Windows, look at the code for non-blocking sockets which will make things clear for you.

Anonymous said...

I wan to make a project wich is named VOIP(voice over internet protocol)..n i need to use socket programming for dat..kindly tell me where i shud start from..pls post me some tutorials dat can give a basic knowledge about this concept.

Vishmadev said...

hi prasanna i am having a problem with connect function...
i dont know why...
i m giving u the code here..plz help me...

int main(int argc, char *argv[])
{

struct MSG {

long int m_type;
int m_txt[MAX_TEXT];
int m_seq;
int m_total_packet;

} m_data;



int sock,conn;
struct sockaddr_in server_addr,client_addr;
int bytes_sent, buffer_length,rcvack=1;


FILE *in;
int f,j=1,k,i;


int total_packet_no=0;
fpos_t pos;
int c;
int size=0;
int nread,len,tran_data;

//argument checking
if(argc!=3)
{
printf("Please enter like the following\n");
printf("./msgtx /path/filename IP Address\n");
exit(1);
}


//opening any file
if((in=fopen(argv[1], "r"))==NULL)

{
printf("Cannot open source file.\n");
exit(1);
}


//calculating the size of the file

while((c=fgetc(in))!=EOF)
size++;

fclose(in);

//calculating the no. of packets

total_packet_no=(size/MAX_TEXT)+1;
printf("total number of packets: %d\n",total_packet_no);
m_data.m_total_packet=total_packet_no;

sleep(2);

//again opening the same file, since rewind is not working, or stat

if((in=fopen(argv[1], "r"))==NULL)
{
printf("Cannot open source file.\n");
exit(1);
}

//converting the file pointer into file descriptor
f=fileno(in);
if ((sock=socket(AF_INET,SOCK_STREAM,0)==-1))
{
perror("Socket");
exit(1);
}

server_addr.sin_family = AF_INET;
inet_pton(AF_INET, argv[2], &(server_addr.sin_addr));
server_addr.sin_port =htons(5050);
bzero(&server_addr.sin_zero,8);
//memset(&server_addr.sin_zero,0,8);
len=sizeof(struct sockaddr_in);


if ((conn=connect(sock,(struct sockaddr *)&server_addr,sizeof(struct sockaddr)))< 0)
{
printf("error entered");
getchar();
perror("Connect");
exit(1);
}

while(j <= total_packet_no && rcvack > 0)
{
// sleep(1);
nread=read(f,m_data.m_txt,MAX_TEXT);
if(nread==-1)
{
printf("read error\n");
exit(1);
}

m_data.m_seq=j;
//displaying the data

bytes_sent = send(sock,(void*)&m_data, sizeof(struct MSG),0);

if(bytes_sent < 0)
{
printf("Error sending packet: %s\n", strerror(errno) );
exit(1);
}

j++;

}

close(sock);
fclose(in);

exit(0);
}



the problem is i am having an error like...socket operation on non-socket...
can u help me out...the server program is okay...)

satya said...

Hi prasanna
this is satya. I want to know how can we execute a unix command at server (c lan) and sent back that result to client and client will disply that result on stdout. we will take command at client, client send that command to server.
please help me out.
thank you
satya

Prasanna Seshadri said...

Hi,

Thats very simple, send the command as a string to the server and use a command like execl (or other exec command) in the server to execute the client command and add the result in a String array and send it to the client.

If you follow my C Code, the client sends a line to the server and replace that line by your UNIX command.

satya said...

if u don't mind can u give just simple code for execl command

satya said...

include stdio.h
include unistd.h
int main()
{
char buf[20];
bzero(buf,20);
printf("Here are the files in:%s",getcwd(buf,20));
execl("/bin/ls","ls","-al",NULL);
return 0;
}

this code is working fine, now how we can redirect this output to a sting instead of Stdout. we can send the string to client.

Prasanna Seshadri said...

Hi,

You have to use popen and pclose for getting the output and status code, I will write a separate section for that, but for the time being use this code.

#include &ltlstdio.h>
#include <stdlib.h>

int main(int argv, char ** argc) {

if (argv != 2) {
printf("Usage: unix_command \"COMMAND TO BE EXECUTED\"");
exit(1);
}

char *COMMAND = argc[1],*readLine, *tmp, *commandResult = "";
FILE * fp;
int status;

fp = popen(COMMAND, "w");

if (fp == NULL) {
perror("Command execution failed");
exit(1);
}

printf("Printing the command output....\n");
while ((fscanf(fp, "%s", &readLine)) != EOF) {
tmp = (char *) realloc(commandResult, strlen(readLine));
commandResult = tmp;
strcpy(commandResult, readLine);
}
printf("\nCommand %s output = %s", COMMAND, commandResult);
status = pclose(fp);
printf ("Command %s return status code = %d\n", COMMAND, status >> 8);
return status;
}

chits said...

hi prasanna ...
i need to send a text file from one system to another ... could u plz help me out ... could u give me the code ...

chits said...

that file transmission should be in socket programming (JAVA)

Prasanna Seshadri said...

Hi,

For transferring files, you may also look at my file upload server which transfers files from client to server which uses java sockets internally.

http://www.prasannatech.net/2009/03/java-http-post-file-upload-server.html

Wirasto S. Karim said...

Thank's

srikanth said...

how to create google addsence account ..
please explain in detail i am intreasted in it but confusing
and
thanks for socket programing tutorial

Prasanna Seshadri said...

Hi,

Would appreciate if you post comments related to adsense in my adsense related post, anyways creating adsense account is very easy, go to adsense.google.com and create one, you need to have a website/blog to create one.

satya said...

hi prasanna

please check this code
char buffer[30];
buffer="ls";
strcat(buffer,"> temp");
system(buffer);
if((fp=fopen("temp","r"))=NULL)

no compliation errors, but this command not writing anything into the temp file. can u check it once again. This is for executing a unix command at server machine and sent back the result to the client.

namratha said...

hello Sir,
I am new to socket programming. I hav taken up a project "implementation of FTP" . I heard that socket programming is necessary for it.
Please guide me what all knowledge should i have, to make my move.
Thank you

Prasanna Seshadri said...

Hi Namratha,

Your first step should be understanding all socket calls, just go through the above code, it will be a right start for you, if you want to feel easy, then I would recommend starting socket programming in a language like java or python, then use C.

There are lots of tutorials and books which may help you for this, once you learn, then FTP will be quite simple.

Prasanna Seshadri said...

For those of you who want to clarify doubts, be specific and clear, also I may not answer all queries because of time constraints, but will try to answer as many as possible.

Hema said...

hai im ramesh,
how to create a connection between the ethernet in a biometric reader with the computer!... here computer acts as a server and the ethernet in reader acts as a client!.. can u tell me how to establish connection between these two systems?
plz guide me prasanna can u give code in "c" for this case?

Prasanna Seshadri said...

Hi,

I am not sure about device driver communication between computers, they have a separate protocol to initiate the connection after the device is detected, you need to go through their manual to get more info.

hema said...

Many thanks prasanna..i.ve gone thro the manuals the ethernet controller we are using is W5100 which is already been interfaced with a ARM controller in the reader,. here we hav to transfer data thro that ethernet by tcp-ip mode to the pc for the finger print enrollment! moreover you are doing a good job for everyone
regards,
hemanandharamesh

Prasanna Seshadri said...

Hi,

Thanks for saying so.

satya said...

int main(int argc, char *argv[])
{
struct hostent *hp;
if(argc !=2) {
fprintf(stderr,"usage: getip address\n");
exit(1);
}
if ((hp=gethostbyname(argv[1])) == NULL) {
herror("gethostbyname");
exit(1);
}
printf("Host name :%s\n",hp->h_name);
printf("IP Address : %s\n",inet_ntoa(*((struct in_addr*)hp->h_addr))) ;
return 0;
}

when I am compleing this code I am getting dereferencing pointer to incomplete type. please help me what the changes I have to make.

thank you
with regards
satya
9291488346

Dileep said...

how to create http packets of video data on server side and how to determine relationship b/t that packets on client side

please give me any solution or suggest me about that problem
thanks in advance

Anonymous said...

I have a problem here.... I use cygwin under windows.. So I get the following problems:

1. When i go gcc client.c, it compiles well. But, when i click on the client.exe, it says the cygwin1.dll is missing

2. When i type $gcc client.exe client.c mno-cygwin, it says tht the sys/socket.h and netint/in.h are missing

What should i do to rectify this problem?

Prasanna Seshadri said...

Did you follow the cygwin manual, you should not be getting the dll errors if you installed cygwin properly, one thing which will help is copy the DLL in the same folder as your executable, that may solve the problem.

Jan said...

He Prasanna,

First of all, thank you for the good post.

I tried to communicate between the java udp server en de c udp client and with no problems.
But when i try to run de java tcp server with the c tcp client it doesnt work. When i run the client the console does not ask about anything to write. its just black and im not able to type anything.

You have any idea what it could be?
Many thanks

Prasanna Seshadri said...

Hi,

Yes I need to work on the Java C combination, when I find time will do that , looks like I need to use a different stream in that case.

Jan said...

thats ok i'm just using the UDP socket now.
But i have another problem. I'm sending information from the c client to the java server. In the java server everything is being put into arrays.
This is going just fine untill 574 times(i've put a counter in it) and then it stops getting anything. But the C client keeps on sending.
In java there is no error message or anything. It keeps running but does nothing.
Any ideas?

Prasanna Seshadri said...

You mean in my code above, let me know so that I can fix it this week when I am free.

Jan said...

Yes in the code you posted above. With the C UDP client sending to the java UDP server.
I also changed the code in the C client at line 24 and 25 to "return 0;" so it keeps on sending.(else it stops after a couple of times).
In java i just have data being put to an array that keeps getting overwritten.
I just can't find what the problem is.

Jan said...

Hej Prasanna I'm very close to the solution now. Where i said i put return 0; i raplaced that with close(0);(line 22 and 23. Earlier i said 24/25 my bad.) to clean the connection. but now im not getting everything in after de moment where earlier it stopped but just some of the data.
so close..

Prasanna Seshadri said...

Thats a good progress, keep hacking on, you will get it.

Jaydev said...

Hi Prasanna
I am currently doing my project and have to transfer a file between one PC to another after a particular time interval in a continuous manner, since the file on 1 PC is a log file that gets updated every second.
I want to connect them by an Ethernet Cable. It would be a great help if you could tell me how I could go about doing the program or some sample programs that I can use for this purpose. Also can I make the file on the talker and listener side in such a way that it can be used for both windows and unix based systems with a small modification.
Any help would be appreciated
Thanks

Jaydev said...

Also i would be wanting to do the coding in C.

Anonymous said...

hi
i m working on a project related to socket prgm i have include WINSOCK2.h at the place of some header files but the remainin gcode is same problm is socket is not being created by socket() it is returning -1 value i m new at this so guid me if u hv any idea regarding this prb i m using DEV c++ compler

fahad said...

hi prassana,

Thanks for your great work.
I am new to socket programming, i want to know whether it is possible to transfer a video stream (video from an IP camera) through socket programming. If so is it possible for me to record the vidoe, play back again, etc plz help me
regards
fahad

Rishi Malviya said...

Hi Prasanna, I have a project for passive analysis of packets and I am having some problem with the sequence no. of TCP rest of things I have figured out and they are all fine. please let me know If you can help me with it. I would really be obliged. waiting to hear from you soon.

Cheers!

shaik said...

sir,
Iam a software programmer in linux..Currently iam working on Qt3.3 on Linux platform..
i need ur help badly ..
i have to develop a server and client program which can communicate thru sockets.
and in server i will have database and my application will be running..
coming to client there should not be any database but thru ODBC settings i should be able to access database of server and should be able to see the values in my application(ie in client).

i know only how to communicate btn server and client thru berkeley sockets ..but this part im finding it difficult /...can u plz guide me???
plz reply as early as possible sir...i wud be v thankful to u !!!!!!

Madhu said...

Hi,

Really nice sample for TCP socket conn. I have just started learning on TCP.

I have a problem while doing forking in server for client connection.

Server :- A
Client :- B, C, D

I have 3 clients which connects to A server and Server tries to fork for
each client.

First client 'B' connects to server. Server generates a fork and client starts
sending the records, which will tail from log file. when any updates are done to file it will
send it to server.

Second client'C' connects to server. Server generates a new fork and client starts
sending the records(line) from log file which will loop infinetly and sends data
for every modulus of 1000 line.

Third client 'D' connects to server. Server need to fork a new child.

Here, I am getting problem while D client tries to connect to A server.
'D' client gets hung up. Until 'C' clients get disconnects from server.

Means I need to press CTL+C to stop the 'C' clients then 'D' client automatically
continues to process the file.

I have also include the SIG{CHLD} and waitpid in my code if any zombie process generates.

Please can you help me out, How the 'D' client also starts the job parallel with other 'B' and 'C' process.

Thanks,
Madhu

meeran said...

Hello All Dear friends
I wanna make socket connection between two computers ( Server and client ) to send data of image from sever to client .. who can help me to make this way ?

Aaron said...

Hello,

You're client/server examples are really useful. They helped me a lot in completing an assignment for one of my classes. I have code that works when running locally (2 terminals). However, the client and server don't seem to communicate remotely. Do you have any suggestions?

meeran said...

Thanks so much if you can send me Code how Server and client together are working to send Data between them by Socket programming

Nawaz said...

could please some 1 tell me how to modify the socket programming example in java so that it can be used to communicate betwenn 2 computers on lan or the internet..please :)

meeran said...

Nawaz
Really i didn' work around Java
easy way to use socket between two more computer ( server / client ) use VB6 it's so simple and implement code of both sides

Nawaz said...

Thank u meeran ... this program is working amazingly fine over lan as well........can please sum 1 tell me how to make it like continous messaging type? meaning in this program after say server sends a msg he has to w8 for a reply to send another 1 ... please sum1 tell me how to make it continous messaging type :) Thankyou ..

sagar said...

Hi prasanna..
Iam new to socket programming. I am trying to accept multiple requests from clientapplication using Tcp Connection.I would like to put all the requests from the clientapplication into Queue and then create 10 threads.Each thread process the mess from from the Queue and sends it to the another peer via UDP for the response.Udp peer process the message and sends to the peer1 via UDP.peer1 sends it back to the application via tcp.Can you give me an idea of how to handle the requests into Queue and threads.I appreciate your advice

sagar said...

Hi prasanna..
Iam new to socket programming. I am trying to accept multiple requests from clientapplication using Tcp Connection.I would like to put all the requests from the clientapplication into Queue and then create 10 threads.Each thread process the mess from from the Queue and sends it to the another peer via UDP for the response.Udp peer process the message and sends to the peer1 via UDP.peer1 sends it back to the application via tcp.Can you give me an idea of how to handle the requests into Queue and threads.I appreciate your advice

Nawaz said...

Prasanna could u please reply to my post??

Anonymous said...

If you're using Beej's showip.c example at http://beej.us/guide/bgnet/output/html/multipage/syscalls.html, the following two lines of the code may give you problems:

addr = &(ipv4->sin_addr);
addr = &(ipv6->sin6_addr);

If you're getting this error:

error: dereferencing pointer to incomplete type

Try putting this at the top of your source:

#include <netinet/in.h>

Cheers!

Matt Borja
Borja Webs, LLC
http://developer.borjawebs.com

vrushank said...

Do you have any tutorials on socket prog. I have done socket prog. before and am applying for a job in the same, thus am looking for a fast track tutorial which will help me clear the interview.

Anonymous said...

hi there mate, this has been really helpful so far, being a novice and new to the field, i was wondering if you could put up a commented version for the 'TCP client' and 'UDP client and server' explaining the lines of code if it is no trouble.

Anonymous said...

...for c programming.

lidya said...

hello mr prasanna thanx for this blog it's so good and useful,,im a newbie to ruby and i just wanted to know how to connect a ruby server and a java client using tcp/ip protocol,,actually ive been through many attempts to connect them in simple examples like just sending hello from the server to the client and vice versa but they all turned out in errors so i would be thankful for any help:)

Anonymous said...

In my machine I have both LAN and WAN IP. In C socket program
How can we distinguish a LAN and wan IP

amanpreet kaur said...

hi Prasanna Seshadri

Could u please help me out in connecting 8051 microcontoller (with network interface card connected to it) with another PC in any network.

thanks

amanpreet kaur said...

hi Prasanna


please tell me how to connect an embedded system to the network.

what are the various steps involved.

can I do so by knowing simple C language.

please give me reply as early as possibe on amanpreetlect@gmail.com
or amanpreet_kaur@rediffmail.com

Mohammed said...

hi prasanna, can u explain the difference between connection oriented(Tcp) and Connectionless(Udp) protocols....

Ashwin said...

Thanks a lot for the TCP Programs...they helped us a lot...thank you...

Anonymous said...

hi all

i have a big problem in my thesis and need help please
my problem is i need to stream video from linux pc to windows pc using c/c++ programming language is there any library or tool compatible with c to do this job?
i try live555 and videolan and opencv and... but i can not solve the problem if you sir can help me with a simple client/server program.

thank you very much

siddeeqhssn@yahoo.com

Ashutosh said...

Hey i m new to socket proggraming....
i have a very sily doubt abt it...
i want to know which tool do you use for programming in c, c++ and also for socket programming???
Do tell me ....thanx

sandy said...

Hello prassana
I am building a server which listens to clients . I am writing a handle (in server)to read the data which client send . I have written a simple client to send data . But my aim is to send data from client continously after few seconds . but this server handle doesnt read it . can u please help me

class ServerHandler (SocketServer.StreamRequestHandler):
'''Request handler handles the multiple request'''

def handle(self):
print " Handling request .... "
rw = ReadWrite.zync_IO(self.request)

self.data = rw.read(1024)
print "Received line: ",

its_yogy said...

Hi al,

Wel i have a doubt abt compiling the program called tcpclient.c

1] i had several errors abt not having header files.. rite from in.h till cdefs.h. But nw tht i have downloaded 'em still no effects.. it does not compile in my Visual Studio 6.0. Any inputs on this.

2] Is there any other way.. for carrying out tcpip communication in C. please guys.. neeed ur helps..

thnx in advance !!
Yogy

Anonymous said...

hey Mr. Prasanna i am very thankful to u for this example.well i m teacher in I.T. . Thanks for sharing this code.

Prasanna Seshadri said...

Thanks for saying so.

Nikunj said...

Hi Prasanna,
I am from Bangalore, India.
Your tutorial helped me alot as I am a newbie.
I have 2 questions to ask..
1. I ran python server program on my machine with server_socket.bind(("My IP", 5000))
and on a different system I ran tcpclient.py with client_socket.connect(("My IP", 5000))
The two sockets dont connect to each other..It flags an error "unable to reach host".
The two systems are on LAN, and same OS, Python version..etc.

2. If I want the two to communicate in a duplex mode i.e sending and receiving at the same time..does it requires thread programming?

Please help.!
Thanks

Mayur Ghatkar said...

please tell me which compiler to use for compiling cpp codes for socket programming.
They are not getting compiled because Turbo C does not have many of the headers mentioned in programs. Is it using Microsoft C++ compiler?

sandy said...

Write the client program and server program in 2 different file with extension of c or c++
like client.cpp
and server .cpp
then in the console in linux(terminal) and in window (command prompt) go to the folder where you your program is and the execute gcc server.cpp and in other teminal gcc client.cpp (in windows different command prompt . Make sure the client uses servers port and ip address to get connected

sandy said...

Its not about which compiler to use , you can use any c++ compilers(gcc,turbo,intel...) , the way you execute is one above

Prasanna Seshadri said...

Use gcc for compilation.

shadyabhi said...

Use of "gets()" should be strongly discouraged. You have used it in your C language server code... Better change it to fgets()

thamanna said...

can we import API in python as we can do it in c#?

fajju said...

HI Mr. SHESHU.. I HAVE GONE THROUGH YOUR CODE AND NOW I GOT SOME DOUBTS REGARDING TECHNOLOGY., HOPE YOU CAN HELP ME OUT WITH YOUR VALUABLE SUGGESTION.. AND MY DOUBT IS...

HOW THIS STREAMING A VIDEO OVER NETWORK HAPPENS... LIKE IN GENERAL NEWS CHANNELS TELECAST LIVE VIDEOS.. RIGHT..?? SO THIS IS HAPPENING OVER WIRELESS NETWORK., BUT I'M NOT FINDING CORRECT GUIDE TO READ ABOUT THE TECHNOLOGY BEHIND THIS.. CAN YOU SEND ANY TUTORIAL GUDIE FOR STREAMING... THANKS IN ADVANCE..

NANI said...

hi sir,

sir am a new bie to socket programming, hav seen the tcp server and client programming in C, it was interesting. I want to try hands on on my windows xp system(using c). hw can i start sir, and a small query should my Local area connection be connected all time???

gmsuresh said...

Hi prasanna,

In the client and server communication im sending continuous messages either client or server the other side(client or server) getting the messages.....i want to store the messages in queue........Can you give me an sample code of how to handle the requests into Queue
/******client code *********/


#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
int sockfd, portno, n,m;
char send_data[1024],recv_data[1024];
struct sockaddr_in serv_addr;
char buff[256]="";
char buffer[256]="";
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");

}
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
serv_addr.sin_port = htons(5000);
connect (sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) ;
if(connect < 0)
{
printf("ERROR connecting");

}
printf("\nenter the message:");
m=fork();
if(m==0)
{
for(;;)
{
fgets(buffer,255,stdin);
n = send(sockfd,buffer,strlen(buffer),0);
if (n < 0)
perror("ERROR writing to socket");
}
}
else
{
for(;;)
{
n = recv(sockfd,buff,256,0);
if (n < 0)
perror("ERROR reading from socket");
else
printf("The return message is %s\n:",buff);
printf("\nRecieved data = %s " , buff);

}
}
return 0;
}



/**********server code **************/
#include
#include
#include
#include
#include
#include
#include

struct my_msg_st {
long int my_msg_type;
char some_text[BUFSIZ]; };


int main(int argc, char *argv[])
{
int sockfd, newsockfd,portno, pid, clilen,s;
// char send_data[1024] , recv_data[1024];
char buffer[256]="";
char buff[256]="";
long int msg_to_recieve = 0;
long int msg_to_send = 0;
struct sockaddr_in serv_addr, cli_addr;
int p,running=1;
int msgid;
char ender[3] = "end";
struct my_msg_st some_data;
msgid=msgget((key_t)1234,0666 | IPC_CREAT);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");
}
else
printf("opening the socket\n");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(5000);
s=bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr));
if(s < 0)
{
perror("ERROR on binding");
}
else{
printf("binding the socket\n");
}
if(listen(sockfd,5)<0)
{
perror("server_listen ERROR");
}
else{
printf("server is ready to connect client\n");
}

clilen=sizeof(cli_addr);
if(msgid < 0)
{
perror("msgget failed with error");
}
while (1) {
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
perror("ERROR on accept");
pid = fork();
if (pid < 0)
perror("ERROR on fork");
if (pid == 0) {
close(sockfd);
p=fork();
if(p==0)
{
printf("\nthe return value is %d\n",p);
if(msgrcv(msgid,(void *)&some_data,BUFSIZ,msg_to_recieve,0)== -1)
{
perror("msgrcv failed with error");
}
printf("You wrote: %s", some_data.some_text);
if (strncmp(some_data.some_text, "end", 3) == 0) {
running = 0;
}

// {
// bzero(buffer,255);
// recv(newsockfd,buffer,sizeof(buffer),0);


// printf("Here is the message:%s\n",buffer);
// }
// }
else
{
for(;;)
{

printf("the parent pid is %d\n",p);
bzero(buff,255);
fgets(buff,256,stdin);
send(newsockfd,buff,256,0);
printf("\n SEND DATA = %s " , buff);
}
}
}
else
{
close(newsockfd);
}

return 0;
}

}}

Costa Mtagwaba said...

Hi hi S.Prasanna
a) I have live data file located in Ubuntu PC, desktop, and it has its own IP Address 10.23.3.19,
b) I have Windows PC with its own IP address 10.23.3.18 ready to use these live data from Ubuntu, or possibly store them in Windows Desktop,
c) They can all contact each other by using IP Address. Both can use python programming,
d) I need to send these data from Ubuntu PC (file ready with data) to Windows PC (file not created and required to store in Desktop) , Continuousily
d) I am novice into socket python programming, I have looked into your blog http://www.prasannatech.net/2008/07/socket-programming-tutorial.html very useful but am totally confused where to put things together, Any help please

costa in Coventry, UK

Anonymous said...

Sir Thanks alot for ur wonderful work well i iam using the windows os does it code will work well??

Anders said...

Thanks!

Anonymous said...

tcpserver.c and tcpclient.c

ERROR in the C code after recv():

Original:
...
char send_data [1024] , recv_data[1024];
.... bytes_recieved=recv(sock,recv_data,1024,0);
recv_data[bytes_recieved] = '\0';

Error:
If you get 1024 bytes, it will be overwrite: recv_data[bytes_recieved] = '\0';

Sollution:
Use 1023 in recv instead of 1024, or change the size of the buffer.

Anonymous said...

Hi I want a perl code as server and java code as client but the codes provided by you are not doing that can u help in this???

Anonymous said...

Hi, please help me out with this. I need to have a client server program where client sends frames( an image) to server. Server should use multiple threads( serving many clients). Either TCP or UDP will do. Operating system is windows.

Please help me.

iqbal said...

write aserver-client to coumnicate b/w them one way

Kedar said...

hello Mr.Prasanna Seshadri...i am new to networking and also to socket programming,but very keen to learn it and i want to pursue my MS in the same field...please suggest me as to where to start from (especially in socket programming)

Kedar said...

hello Mr.Prasanna Seshadri...i am new to networking and also to socket programming,but very keen to learn it and i want to pursue my MS in the same field...please suggest me as to where to start from (especially in socket programming)

Prasanna Seshadri said...

Hi,

This article is just an introduction, for more details, please see the referred books, they can be used for in-depth study.

Anonymous said...

thx for that tutor

wfg enzo

Anonymous said...

Great tutorial, Mr.
However, I had to make one change for successfully running the tcpclient.c with the TCPServer.java.
When compiling the client, I got a warning: the `gets' function is dangerous and should not be used... so when running, the server can send messages to the client but no viceversa. Googling I found an alternative to 'gets', it's 'fgets'.
So I change line 58:
gets(send_data);
to:
fgets(send_data,1024,stdin);
And then the communication succeed.
Hope this help.
Thanks and good Luck!!!

Prasanna Seshadri said...

Thanks for your comment, I will look into it.

TEJA..... said...

first of all i want to congratulate to provide a good blog for prorammers..n could u pls tell diff b/w server and echo server...

life is meaningful said...

hi..prasanna..could you please explain me how to send a file(any type) from client to server in tcp.

thankyou

Prasanna Seshadri said...

It's easy if you go through these code patiently, try spending some time to understand, that's the best way to learn.

KANDIMALLA's said...

Hi Mr.Prasanna i am very glad to find this blog and thanx a lot for your support.I am new to Socket Programming. I need to have implement
that a server can handle multiple connections, can send the video data packets based on the Round Trip Time of the Paths
A client that can receive the video data from multiple connections and arrange the video data packets in a sequential order to Play

Please help me

Thanks in advance .............


a client that can receive the data from multiple connections and arrange it properly.

Vinaykumar H S said...

Hello Prasanna,
Thanks for sharing wonderful article. I am little messed up. Please suggest me if I can do this or not. I have a software that outputs video in UDP protocol. I am using it on a areal system, I mean On the UAV(Unmanned Areal Vehicle), to be in precise. Main problem to me is that, I Dont have a WLAN link, as it does not give enough range. Instead I have a transceiver capable of transmitting from UAV to our ground station.

I am looking, is there any chance by which I can send the UDP packets through my transceiver. My transceiver accepts digital bit streams. Please help me go about it. I don't have any previous experience on protocol stuff, I am learning for this project.

What I am exactly looking for is something like, if I can make UDP packets to sit on a queue connected to my transceiver, and on other end vice versa.

Thanks in advance

Prasanna Seshadri said...

I think logically you can route UDP packets through different network, but for this first you need to establish the routes between your transceivers and then based on the destination address and the route each one can transmit the packets to the next one in the route till destination is reached, it can be done.

justkar4u said...

Hi Mr.Prasanna,

I wish I could become a programmer like you some day :)I am student at CSU-Sacramento. Your blog really helped me a lot !! Thanks a ton...

Regards
karthik

Prasanna Seshadri said...

Thanks for saying so, by continuous learning, anyone can become better.

kailu said...

Hi, i am new to socket programming in c, so plz help me, that which book i can refer so that i can able to write the code on socket.........



Thank u........

ram said...

Hi Prasanna,

I am very newbie to socket programming.When i scarrter through client and server program,you are using same port number in both client and server program,But in real time,we are not really sure at which port the server is performing listen() primitive.When i try to excute the same code with different port numbers,its failing.Is there any way to design the same program without knowing server port number.

EX:When we initate a gtalk session,The client(our host) completely unaware of server port at which gtalk server excuting the listen() primitive.

Can you please explain me
1)How this will work(gtalk communication)

Rajesh said...

Hello,
I want to retrieve website user's MAC address (and processor number is possible) to avoid sharing of user ID and password among the users. We earlier tried retrieving MAC address, but it only worked for old IE versions. New versions of IE browser and all other browsers do not help in this.
I suppose, may be a small program needs to be installed on remote user's machine when he/she subscribes to the website and when such user logs on to the website, the details such as MAC address and processor number can be verified online.
I request your help in this.
Best regards.

guruji said...

Hi,I'm newbie to socket programming.I am able to write code for tcp server and client.I want to use "FINGER" with tcp server and client.please help me...!!

Anonymous said...

hi,
i like this website of urs,
i was wandering if ye kould plz guide me the fundamentals of socket programming, because i am totally new to this....
thnx

Anonymous said...

Hey prasanna.. good work.. have a small query here... how do we handle multiple client connections in the tcpserver program ???

Prasanna Seshadri said...

The best way to handle multiple clients is to use threads or you can fork a process for every client.

Sonia said...

A very informative one. Thanks.

Anonymous said...

halo mr.prasanna...
i've an asignment to simulate ftp process(C and S programs) using tcp socket programmig inC....it should be able to:
-authorize
-list the files at server
-download the files in client machine
can u send me the code for this as my code is not getting compiled--to
vk_bookworm@ymail.com

adwait said...

hi, i have to do my final year project based on socket programming in java, that will allow server to monitor the lan as well as provide facility of blocking unwanted http by client, allows ftp, chatting, etc.. i dont have any idea about socket programming.. please guide me...

Umair Aziz said...

Hello Everyone..i am new to socket programming.I want to know how one can program a remote-access control using socket programming that means accessing your PC from remote place using networks

Yogesh said...

I want help in writing a client-server UDP socket mutual communication program in c language in which both should listen to same port..
I am getting following error

Bind: Address already in use
plz help

Priyanka said...

Hello to all socket expert programmer...
I also facing same problem as yogesh..
plz help

Prasanna Seshadri said...

Two applications can't listen from a same port on the same system, change the TCP/UDP ports.

Anonymous said...

Hi Prasanna,

I am new to this socket programming. I have client in Java and server written in C. I have established the connection from the client and created the input stream. I need to read from the server each message (packets) prefixed with some header.
I need to read in the same order in the client. Can I just simply use read(buff[],int off, int len)?

How can I read the data from C server in my Java client? Should I be using JCAP?

Anonymous said...

how can i make a udp server serving multiple clients...i mean i know we use multithreading but i don't get how to use it any idea...??

Anonymous said...

Hy Prasanna i'm a students in IT Department in my university. i'm newbe...

can you tell me who to get IPaddress if console program just type web address :
for example :
>% www.google.com
IP : 205.85.132.104
class : C

thank's before....

Anonymous said...

hi sir this is my problem and i'm new to java..completely..Write a Java socket program on Unix to demonstrate UDP client-server
communication where the client receives the acknowledgement from
the server and the server displays the following:
Data received from the client.
The acknowledgement sent to the client.

Sonal said...

Hi,
I am trying to have directory hierarchy(in Tree) from server machine on client.. can you please tell me how can i so this?
Awaiting for reply...
Thanks.
Sonal

Anonymous said...

Best Ever socket programme tutorial and examples.....nice work keep it up

kalpu said...

hi.
please can u send me the program for sending video within LAN...in java

shivanshu said...

sir,
I am a .net programmer.i need ur help badly ..
i have to develop a server and client program which can communicate through sockets.
and in server i will have database and my application will be running..
Server will get user credential from client and have to send user details to the client.my database in mysql.
please help me out.Its very important for me.

praveen katikar said...

I found your blog yesterday and i went through that , i like Your blog very much which helps many programmers.
Actually i want to establish connection between two systems(pc or latops) using IP address (peer to peer connection) ,my question that it is similar to socket program or not , basically iam not a programmer and i dont have much knowledge on this topic, iam pursuing my master in Sweden in Telecommunication.If possible can you provide code for p2p connection in c Language.Please consider this comment and reply me, your advise is much valuable to me.

praveen said...

Hi prassana
I found your blog yesterday and i went through your blog , i like Your blog very much which helps many programmers.
Actually i want to establish connection between two systems(pc or latops) using IP address (peer to peer connection) ,my question that it is similar to socket program or not , basically iam not a programmer and i dont have much knowledge on this topic, iam pursuing my master in Sweden in Telecommunication.If possible can you provide code for p2p connection in c Language.Please consider this comment and reply me, your advise is much valuable to me.

Prasanna Seshadri said...

Yes, it's related to sockets.

Anonymous said...

Hye sir..i need to transfer file using udp between two computers....

its must have GUI..a button that browse file from the pc to send to other pc....

Is there any hints or done projects like this..im short of time...

Thanks

praveen said...

Thanks for replying

I am searching for the codes related to P2p in c language, so can u post your socket code in c langague for connecting two systems or laptops.
Best Regarads
Katikar.praveen

Anonymous said...

this codes are really helpfull....
thanks for the blog....
:)

Paul Jewell said...

Thanks for that! For information, Beej's guide has moved to:
beej.us/guide/bgnet/

standupdad said...

Prasanna,

Thank you for your blogging posts. In researching trying to find a tutorial on socket programming in python, I found your site.

A little about me... I am not a programmer or developer, but am looking to create an Android app with the use of Google's App Engine and App Inventor. The app, at it's most basic, will allow the phone user press button 1, to send document 1 to an IP address entered by the phone user. That ip address will be a device that my company makes that will act a specific way once that doc 1 is sent to it via ip. I can do the same thing with hyperterminal in windows, but want to do it on an Android phone instead. An ultimate version of this application will be to use an application that uses the camera to read barcodes whereby I can merge the 1D barcode data into the same doc 1 being sent to the user assigned ip.

If because I am working with App Engine and App Inventor, you believe that I should be looking and learning another way, please advise.

Standupdad

lienys said...

Prasanna,
am a cuban student, and i found your blog reserching about socket programming.
i study computer science @ university of havana, cuba. and am on my last year making my tesis. i will build a cluster, and i need a lot knoledge about sockets.
i want to say thanks 4 blogging information very useful.

Prasanna Seshadri said...

Standupdad, in your case, you should be looking at a set of SDKs which should be doing that thing, there is a python something like Python for S60 for your application, that will be the convenient way to do that.

Check out in http://wiki.forum.nokia.com/index.php/Nokia_Open_Source#S60

satish said...

Mr.Prasanna Seshadri,
I'm using borland Developer Studio C++ 2006. I'm not able to do Socket programming(PC to PC) or socket communication. Can you please help me in this regard.

Satish.

Simha said...

Hi Prasanna,

I am learning socket programming, I have an assignment where i need to create a packet injector, which will be 1. Complete packet with a GRE Header, a custom packet structure, followed by IP, TCP layers.

Do you have any example or a sample code ?.

Anonymous said...

Hi Prasanna,

I want to know how to do with a revc() msg with blocking and send() msg with nonblocking on TCP server using the same port for sending and recieving messages.Is it possible to have a blocking recv() call till the trigger is recieved and non blocking send () call. And I want know how to do this. Its very urgent. Thanks in advance....

NITIN KUMAR said...

plz..wryt a program in c language.. using TCP ..the client should send a file to a server which should calculate the numbers of lines in the files and send the result to the client for displaying it ?? plzzz help me out solving dis prooblm...

Anonymous said...

hi, not sure if you know, but of all the links that google shows up at the top, for simple udp client server (in c), only yours works! even the experts exchange has given a static ip for listening in server code. Nicely written, keep it up!

sudheendra said...

hi,
i want to send packets from client to server so please suggest me how to design packets?

Anonymous said...

Do these samples work on Windows and Linux? If not, what is an example that works on these platforms? What changes might I need to make?

tamilactor.gallaries said...

hi iam balaji iam doing mca....
i have my final year project doing a tcp/ip socket comminication b/w the two system must using a turboc coding &turboc comiler dont use any unix,brolandc++,or java thats my task pls help me!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1

Anonymous said...

Hi prasanna,
is it possible to create raw socket in windows 7 OS? i tried creating raw socket using WSASocket() method.
but when i'm executing application as administrator (right click on the exe and select run as administrator) raw socket got created. so how can i create raw socket without having any admin rights in windows7. any services has to be run prior to launch the application?
awaiting for ur response

Norlesh said...

Hi Prassana, thank you for putting the bare basics in one place - I just needed to make a quick hack so I could role a java library into a simple service to use from python.

Considering how uncomfortable I find java it was becoming a daunting task. Thanks to your code its 80% done.

One observation: The java code expects newlines to be sent while the python does not. It would be nice if you normalized the language examples so the client and server from different languages could interact without modification (by adding line feeds to the python messages I was able to mix the python and java implementations easily)

QaMeR said...

Hi i am ew to LINUX please help me i want to develop a application over UDP on multiple servers... Please Help me ...

Develop a application over UDP
• The client sends the message “Hello World” to server1, server2 and server3.
• The server1 receives the message and prints on its standard output.
• The server2 receives the message and prints on its standard output.
• The server3 receives the message and prints on its standard output.

Anonymous said...

Sir,
can you please give me some basic code for establishing multiple clients - single server communication
using sockets in java

Prasanna Seshadri said...

If you understand the java code here, handling multiple clients should be easy.

Clue: Create multiple threads for each client, look at the thread programming article in this blog.

Anonymous said...

@prasanna: may i ask a question on how to network in jMonkeyPlatform??
- actually we were trying to make a 3D game that can be played in LAN or Wireless.,but we dont know how..??
-would you like to help us in networking the game??

Anonymous said...

Thank u sir,
multithreading worked... I hav one more doubt...
From a single client system i am trying to send many requests from different ports to the server.
After sending requests from these ports i need to make them wait on those ports but at the same time
the other normal processing of sending requests to server should carry on... can u pls give some idea on how to do this.

chinn said...

Thanks for your article.But i have a question .What is the difference between a socket and a protocol?Java consists of 3 sockets.TCP,UDP and Multicast sockets.A protocol consists of IP address and a socket also consists of IP address and a Port.So is socket and protocol are same ?

Sunny said...

Hi I want to do live video streaming between two PCs over wifi in adhoc mode. How can Ido it with udp socket? Plz help me!!!!!!!!!!!

Anonymous said...

Hi
thanks a lot for the article it really helped me.
how can i set my clients port number?

Viks said...

Hi.This is Vivek this article was very useful.
However i want to exchange data between 3-4 systems.My client and server are in C prog.How do i go abt this.Could you mail me your reply to vivekvenkat88@gmail.com.

This is a part of a game project.I need to connect 4 systems in my initial state.How do i exchange data between them?

kareti said...

i am close to Java and so i would like to work with it! i like to write some program to work with raw sockets! so I need some help! a small program in it will help me a lot!! thank u very much.

Surjeet said...
This post has been removed by the author.
Surjeet said...

Thanks a LOT... really this document helped a lot.

Dan said...

what does a file descriptor mean?

Abhishek said...

sir iam abhishek studying engg in computer science. i am willing to learn python script language as my project is based on network lab experiments using python. will you please suggest some books and references for making thorough about network experiments like socket programming in python?

Anonymous said...

hi i want to implement the java rmi mechnism for accessing method of remote systems

Anonymous said...

Dear Prasanna,
You posted this tutorial in 2008 and still continue to attract attention. Good job! You should be proud of yourself.

Prasanna Seshadri said...

Thanks, hope it's useful to many.

Zedd said...

hello, this helped. I agree with the person who commented before me: Good job on having such an awesome blog that has been going for three years.

Anonymous said...

Sir, can u pls tel me how to write to a file in java in a formatted manner. Eg. like below:

First,
Second,
Third

i.e.. each word in a new line by inserting new line into the file ?

Parimal said...

hi,
I have a problem with a recv function, based on a particular network... if i use a tata docomo 3g data card i can't receive the data n' just close the socket.. but if i use other data card like tata photon then i can receive data through socket....this is a tcp connection oriented connection....
> so, is there any kind of network specific socket connection is there to receive data via recv function ?

Pushkar Saraf said...

I do not want to use the server-socket.

I just want to communicate between the clients ( A peer-to-peer n/w)

Can anyone help me regarding this...

«Oldest ‹Older   1 – 200 of 207   Newer› Newest»

Copyright © 2008 Prasanna Seshadri, www.prasannatech.net, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.