Tuesday, February 19, 2008

[Programming] Sockets programming on Linux/Unix

Last time we introduced the fundamental of sockets programming and gave an example (WinSock) on the Windows platform.
In deed, socket interface was first introduced in UNIX. In UNIX, socket interface is actually an extension of the concept of a pipe.
However, sockets are created and used differently from pipes because they make a clear distinction between client and server, and they can implement multiple clients attached to a single server.

Again, let's briefly go over the principles of sockets programming:
1) First, a server application creates a socket using the system call socket.
2) Next, ther server process gives the socket a name, using the system call bind.
3) Then the server process waits for a client to connect to the named socket using the system call listen, which creats a queue for incoming connections.
4) For incoming connections, the server can accept them using the system call accept.
5) When the server calls accept, a new socket is created that is distinct from the named socket. This new socket is used only for communication with this particular client. The named socket remains for further connections from other clients.
6) Once a connection is established, a two-way communication will be available between the server and the client. They can communicate with each other using sytem call read/write for AF_UNIX protocol or send/recv for AF_INET protocol.
7) After communication, a system call close or shutdown is called to release the named socket.

Client side:
1) The client creates an unamed socket by calling socket.
2) Then the client uses system call connect to establish with the server by using the server's named socket as an address.
3) If the connection is accepted by the server, then the client can communicate with server using read/write for AF_UNIX protocol or send/recv for AF_INET protocol.
4) Similarly, when communication is finished, a call of close/shutdown is called.

Here's a very simple example of socket server and client programs.

// Local server

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
int server_socketfd, client_socketfd;
int server_len, client_len;
struct sockaddr_un server_address;
struct sockaddr_un client_address;

server_socketfd = socket(AF_UNIX, SOCK_STREAM, 0);

server_address.sun_family = AF_UNIX;
strcpy(server_address.sun_path, "server_socket");
server_len = sizeof(server_address);
bind(server_socketfd, (struct sockaddr *)&server_address, server_len);

listen(server_socketfd, 10);
char s_sendbuf[] = "Welcome to server.";
char s_recvbuf[255];
printf("Server waiting\n");

client_len = sizeof(client_address);
client_socketfd = accept(server_socketfd, (struct sockaddr *)&client_address, &client_len);

read(client_socketfd, s_recvbuf, 255);
printf("Message received from client: %s\n", s_recvbuf);
write(client_socketfd, s_sendbuf, strlen(s_sendbuf)+1);

// Local client

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

int main()
int socketfd;
int length, result;
struct sockaddr_un address;
char sendbuf[] = "Hi, this is client 1.";
char recvbuf[255];

socketfd = socket(AF_UNIX, SOCK_STREAM, 0);

address.sun_family = AF_UNIX;
strcpy(address.sun_path, "server_socket");
length = sizeof(address);

result = connect(socketfd, (struct sockaddr*)&address, length);

perror("Error:client 1");

write(socketfd, sendbuf, strlen(sendbuf)+1);
read(socketfd, recvbuf,255);
printf("Greeting from server: %s\n", recvbuf);


Anonymous said...

Hi !.
might , probably curious to know how one can collect a huge starting capital .
There is no need to invest much at first. You may start to receive yields with as small sum of money as 20-100 dollars.

AimTrust is what you thought of all the time
The firm represents an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

It is based in Panama with affiliates around the world.
Do you want to become an affluent person?
That`s your choice That`s what you desire!

I feel good, I began to take up real money with the help of this company,
and I invite you to do the same. If it gets down to select a correct partner utilizes your savings in a right way - that`s AimTrust!.
I make 2G daily, and my first investment was 500 dollars only!
It`s easy to join , just click this link http://yrohoreg.lookseekpages.com/ofegogu.html
and go! Let`s take this option together to feel the smell of real money

Anonymous said...

You may probably be very curious to know how one can manage to receive high yields on investments.
There is no need to invest much at first.
You may commense to get income with a money that usually is spent
on daily food, that's 20-100 dollars.
I have been participating in one company's work for several years,
and I'm ready to share my secrets at my blog.

Please visit my pages and send me private message to get the info.

P.S. I make 1000-2000 per daily now.

http://theinvestblog.com [url=http://theinvestblog.com]Online Investment Blog[/url]

Anonymous said...


[b]Xrumer SEO Professionals

As Xrumer experts, we possess been using [url=http://www.xrumer-seo.com]Xrumer[/url] fitted a large immediately for the time being and remember how to harness the enormous power of Xrumer and go off it into a Banknotes machine.

We also purvey the cheapest prices on the market. Numberless competitors see fit charge 2x or even 3x and a lot of the opportunity 5x what we debt you. But we feel in providing gigantic mending at a low affordable rate. The large direct attention to of purchasing Xrumer blasts is because it is a cheaper alternative to buying Xrumer. So we aim to abide by that mental activity in rebuke and provide you with the cheapest censure possible.

Not only do we have the best prices but our turnaround in the good old days b simultaneously for your Xrumer posting is super fast. We will take your posting done to come you discern it.

We also produce you with a sated log of affluent posts on different forums. So that you can notice also in behalf of yourself the power of Xrumer and how we have harnessed it to help your site.[/b]

[b]Search Engine Optimization

Using Xrumer you can expect to distinguish thousands upon thousands of backlinks over the extent of your site. Myriad of the forums that your Site you settle upon be posted on have exalted PageRank. Having your tie-in on these sites can truly mitigate found up some crown rank endorse links and really riding-boot your Alexa Rating and Google PageRank rating through the roof.

This is making your site more and more popular. And with this increase in popularity as familiarly as PageRank you can expect to witness your area absolutely rank high-pitched in those Search Mechanism Results.

The amount of transportation that can be obtained aside harnessing the power of Xrumer is enormous. You are publishing your plat to tens of thousands of forums. With our higher packages you may still be publishing your position to HUNDREDS of THOUSANDS of forums. Imagine 1 post on a in demand forum will usually enter 1000 or so views, with communicate 100 of those people visiting your site. Now devise tens of thousands of posts on celebrated forums all getting 1000 views each. Your traffic will withdraw sometimes non-standard due to the roof.

These are all targeted visitors that are interested or singular in the matter of your site. Envision how assorted sales or leads you can achieve with this titanic number of targeted visitors. You are truly stumbling upon a goldmine primed to be picked and profited from.

Reminisce over, Traffic is Money.



Anonymous said...

My friend and I were recently discussing about how technology has become so integrated in our day to day lives. Reading this post makes me think back to that discussion we had, and just how inseparable from electronics we have all become.

I don't mean this in a bad way, of course! Ethical concerns aside... I just hope that as memory becomes less expensive, the possibility of downloading our brains onto a digital medium becomes a true reality. It's one of the things I really wish I could see in my lifetime.

(Posted on Nintendo DS running [url=http://kwstar88.zoomshare.com/2.shtml]R4[/url] DS Ting2)

Anonymous said...

Dismiss Slow Downloads With NZB Files You Can Hastily Search HD Movies, PC Games, MP3 Singles, Software & Download Them at Fast Rates

[URL=http://www.nzbsrus.com][B]Usenet Search[/B][/URL]

Anonymous said...

Approve of Our Mournful Prices at www.Pharmashack.com, The High-level [b][url=http://www.pharmashack.com]Online Chemist's [/url][/b] To [url=http://www.pharmashack.com]Buy Viagra[/url] Online ! You Can also Espy Controlled Deals When You [url=http://www.pharmashack.com/en/item/cialis.html]Buy Cialis[/url] and When You You [url=http://www.pharmashack.com/en/item/levitra.html]Buy Levitra[/url] Online. We Also Departmentalize a Staggering Generic [url=http://www.pharmashack.com/en/item/phentermine.html]Phentermine[/url] On the duration of Your Victuals ! We Remove up Opprobrium stamp [url=http://www.pharmashack.com/en/item/viagra.html]Viagra[/url] and Also [url=http://www.pharmashack.com/en/item/generic_viagra.html]Generic Viagra[/url] !

Anonymous said...

Predilection casinos? engage this sprouts [url=http://www.realcazinoz.com]casino[/url] leader and striving online casino games like slots, blackjack, roulette, baccarat and more at www.realcazinoz.com .
you can also deposit our untrained [url=http://freecasinogames2010.webs.com]casino[/url] orientate at http://freecasinogames2010.webs.com and worst extremely known folding metamorphose !
another remodelled [url=http://www.ttittancasino.com]casino spiele[/url] routine is www.ttittancasino.com , as opposed to of german gamblers, delineate forth beneficent online casino bonus.

Anonymous said...

limit rather than of all to jilt to this gratis [url=http://www.casinoapart.com]casino[/url] ancillary at the vile [url=http://www.casinoapart.com]online casino[/url] finished with 10's of … la eminence [url=http://www.casinoapart.com]online casinos[/url]. tame [url=http://www.casinoapart.com/articles/play-roulette.html]roulette[/url], [url=http://www.casinoapart.com/articles/play-slots.html]slots[/url] and [url=http://www.casinoapart.com/articles/play-baccarat.html]baccarat[/url] at this [url=http://www.casinoapart.com/articles/no-deposit-casinos.html]no visit a a postcard down casino[/url] , www.casinoapart.com
the finest [url=http://de.casinoapart.com]casino[/url] against UK, german and all to the world. so after the mind [url=http://es.casinoapart.com]casino en linea[/url] confirmation us now.

Anonymous said...


I mostly visits this website[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url]jinghaoxu.blogspot.com really contains lot of useful information. I am sure due to busy scedules we really do not get time to care about our health. In plain english I must warn you that, you are not serious about your health. Recent Research shows that nearly 90% of all U.S. grownups are either chubby or overweight[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url] Therefore if you're one of these citizens, you're not alone. In fact, most of us need to lose a few pounds once in a while to get sexy and perfect six pack abs. Now the question is how you are planning to have quick weight loss? You can easily lose with with little effort. You need to improve some of you daily habbits to achive weight loss in short span of time.

About me: I am blogger of [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss tips[/url]. I am also health trainer who can help you lose weight quickly. If you do not want to go under difficult training program than you may also try [url=http://www.weightrapidloss.com/acai-berry-for-quick-weight-loss]Acai Berry[/url] or [url=http://www.weightrapidloss.com/colon-cleanse-for-weight-loss]Colon Cleansing[/url] for quick weight loss.

Anonymous said...

[url=http://www.onlinecasinos.gd]casinos online[/url], also known as given casinos or Internet casinos, are online versions of sfa ("buddy and mortar") casinos. Online casinos green uncover gamblers to fling and wager on casino games from manager to foot the Internet.
Online casinos habitually offer odds and payback percentages that are comparable to land-based casinos. Some online casinos instal forth higher payback percentages as a countermeasure with a viewpoint dwelling automobile games, and some promulgate payout participation audits on their websites. Assuming that the online casino is using an correctly programmed unsystematically diversified generator, boom games like blackjack comprise an established shilling-mark edge. The payout incise up during these games are established at unthinking the rules of the game.
Uncountable online casinos say-so discernible or seize their software from companies like Microgaming, Realtime Gaming, Playtech, Cosmopolitan Prank Technology and CryptoLogic Inc.

Anonymous said...

top [url=http://www.c-online-casino.co.uk/]uk casinos online[/url] check the latest [url=http://www.casinolasvegass.com/]las vegas casino[/url] autonomous no deposit hand-out at the chief [url=http://www.baywatchcasino.com/]baywatch casino