Perlfect Solutions

Perl, Sockets and TCP/IP Networking.

An simplified introduction to sockets

Sockets are a mechanism that allows programs to communicate, either on the same machine or across a network. The way it works is pretty simple: Each machine on a network is identified by some address. In this tutorial we will talk about tcp/ip networking, so by network address we mean an IP address. (like 192.168.4.4) Apart from the IP address that specifies a machine, each machine has a number of ports that allow handling multiple connections simultaneously.

A program that wishes to receive a connection from another program, asks the operating system to create a socket and bind it to some port. Then the program sits and listens on the socket it has created to receive incoming connections. The other program also creates a socket for communicating witht he receiver. The caller needs to specify the IP address and the port number of the receiving end. If all goes well, and as we will see shortly, the two programs establish a communication through the network using their sockets. The two programs may exchange information, each by writing to and reading from the socket it has created.

Can I do this with Perl?

Sure. Perl provides support for the socket API natively. Although the interface is not that bad anyway, there is also a very convenient module, IO::Socket that works like a wrapper on the native API and provides a simpler and easier way to deal with sockets. We'll use IO::Socket in this tutorial to demonstrate writing two simple programs that communicate with sockets.

The Receiver

The first thing we need to do is to create a socket. We will use it to receive connections. The code below shows how to create a receiving socket. Note that we need to specify the local hostname and the port to which the socket will be bound. Of course, if the port is already in use this call will fail. Also note the 'Listen' parameter: this is the maximum number of connections that can be queued by the socket waiting for you to accept and process them. For the time being we will only accept a maximum of one connection at any time. (This means that a connection attempt while we're dealing with another connection, will return with an error like 'connection refused') Finally the 'Reuse' option tells the system to allow reuse of the port after the program exits. This is to ensure that if our program exits abnormally and does not properly close the socket, running it again will allow opening a new socket on the same port.

1 use IO::Socket; 2 my $sock = new IO::Socket::INET ( 3 LocalHost => 'thekla', 4 LocalPort => '7070', 5 Proto => 'tcp', 6 Listen => 1, 7 Reuse => 1, 8 ); 9 die "Could not create socket: $!\n" unless $sock;

Now the socket is ready to receive incoming connections. To wait for a connection, we use the accept() method which will return a new socket through which we can communicate with the calling program. Information exchange is achieved by reading/writing on the new socket. The socket can be treated like a regular filehandle.

10 my $new_sock = $sock->accept(); 11 while(<$new_sock>) { 12 print $_; 13 } 14 close($sock);

The Caller

The other side of the communication is even simpler. All we need to do is to create a socket specifying the remote address and port. The constructor will return a socket object after the connection has been etablished, and we may start sending data right away by writing onto the socket like any other filehandle.

1 use IO::Socket; 2 my $sock = new IO::Socket::INET ( 3 PeerAddr => 'asomatos', 4 PeerPort => '7070', 5 Proto => 'tcp', 6 ); 7 die "Could not create socket: $!\n" unless $sock; 8 print $sock "Hello there!\n"; 9 close($sock);

Go ahead and try it!

You can easily try out the example programs above. All you need to do is execute the receiver first and then the sender. On the receiver end, you will see the line "Hello there!" printed on the terminal screen. If you do not have a network, you can still use 'localhost' for the hostname of both the receiver and caller just to test it out.

Synchronization

An important issue to consider in this style of communication is that the two ends must follow a commonly-agreed procedure of data exchange. Otherwise it is very easy to end up in a deadlock situation where either both ends try to read, or both ends try to write. Ther is no way to guess whether the other end has finshed sending data, unless there is some protocol of communication between them that denotes logical sections of the communication in the contents of the transmitted messages. In the example above, the model is very simplistic: The caller sends a message and closes its end of the connection, while the receiver just reads the data until it's all finished.

Usually client-server transactions consist of a caller (the client) sending a request, followed by the receiver (server) sending back a reply. In order for the server to understand when the request is finished, there is some agreed marker (such as two consecutive empty lines, or a line saying "END REQUEST") that denotes the last line in the request. The server, starts sending its reply only after this line has been received, and afterwards closes the socket. The receiver, after sending the entire request switches to reading until the socket is closed, so it will receive the reply. More complex schemes can be established in a similar mannere, according to your needs and taste. What is important is to make sure that the two ends of the communication have a way of knowing when to speak and when to listen, thus avoiding the possibility of getting locked up.

Online Documentation/Tutorials

  • Network Programming in Perl - a well-written introduction to network programming with practical examples.
  • The documentation of the Socket and IO::Socket modules that comes with your perl distribution should be a valuable reference.
  • There's also an article on filhandle multiplexing with select() in which we describe a method commonly use to manage multiple sockets on the same thread.

Comments

Your name:
Your comments:

Security check *

 

32to28   

Posted at 5:27pm on Monday, March 5th, 2007

Great article, helps a ton. Great for beginners, can modify it to your own chat application. Thanks.

Akshat Mithal   

Posted at 11:16am on Sunday, April 8th, 2007

Thanks it was a great note..

I created my own successful script for the first time.

Thanks

Soy4soy   

Posted at 12:14pm on Friday, April 20th, 2007

This helped me pick perl up where I left off years ago... thanks!

rajiv   

Posted at 11:21pm on Thursday, May 17th, 2007

Thanks it was a great note..

Emin Gabrielyan   

Posted at 6:14am on Monday, May 21st, 2007

The listener script of the example does not work with UDP

Emin Gabrielyan   

Posted at 12:35pm on Monday, May 21st, 2007

Here is a script for receiving and printing UDP packets:
===

use IO::Socket;
$server = IO::Socket::INET->new(LocalPort => '5060',
Proto => "udp")
or die "Couldn't be a udp server on port $server_port : $@n";

my $datagram;
my $MAX_TO_READ = 2048;

while ($user=$server->recv($datagram,$MAX_TO_READ))
{
print "---n";
print $datagram;
}

close($server);


===
Here is the screenshot of the script, which receives REGISTER messages from a SIP phone:
===
$ perl a5.txt
---
REGISTER sip:192.168.1.8 SIP/2.0
Via: SIP/2.0/UDP 192.168.1.10;branch=z9hG4bK994c1f6fcb609bef
From: ;tag=dace27af55f4699b
To:
Contact:
Supported: replaces
Call-ID: 599f793881392bc1@192.168.1.10
CSeq: 100 REGISTER
Expires: 150
User-Agent: Grandstream BT110 1.0.8.33
Max-Forwards: 70
Allow: INVITE,ACK,CANCEL,BYE,NOTIFY,REFER,OPTIONS,INFO,SUBSCRIBE
Content-Length: 0

aussie   

Posted at 4:52pm on Wednesday, May 30th, 2007

Well written, easy to follow and very informative.

Keep up your good work!

tejaswi   

Posted at 3:11am on Wednesday, June 13th, 2007

Can i get a simple perl server script DGRAM

Sam,.   

Posted at 5:50am on Thursday, June 21st, 2007

Great article. it helped me a lot to understand the socketing very easily.. thanx a lot..

Sam   

Posted at 2:47am on Friday, June 22nd, 2007

This helped me a lot. could you please post an article like this with forking, threading using socket programming?

Guilherme Arthur   

Posted at 5:17pm on Friday, June 22nd, 2007

Dude!
You saved my life!
XD
Thankx very much!
=D

vijay   

Posted at 12:00am on Sunday, July 1st, 2007

Great article. it helped me a lot to understand the socketing very easily, this is giving the information , how it works well. first of all, if i want to know what is TCP/IP and Perl ( I Understand the functionality of TCP/IP), can any one expalin me from scratch. it will be useful in my QA Career

Anonymous   

Posted at 12:18am on Friday, July 6th, 2007

nice way to do cl-server perl script

anonymous   

Posted at 6:28am on Monday, July 23rd, 2007

nice, this article helped me a lot, keep it up, next one do UDP and maybe find a way to use udp with the quake2 protocol

Smaregow   

Posted at 9:47am on Tuesday, July 24th, 2007

Hi, Can any one help me in solving my questions...my project is some thing like explained below:

My project configuration is something like this...

Clients .Net Message Server Various Servers

TCP/IP is between Clients and .Net message server...and .Net message server is with other servers through COM.

I have 10 clients application and each client has arround few messages...those messages(request) will be send to .Net Message Server which will routes these requests various other Servers and gets the appropriate responses.

By keeping all input messages in the FLAT File I want to Automate the sending and receiving messages using the PERL script and also I want to compare the receving messages aginst the Existing good known results.

My basic questions are....
Is it possible to automate this using PERL script? OR

Do you recomend any other scripting tool to automate this project?

Could any body please help me in taking the right decision?

Many Thanks in Advance,
Smaregow

colin   

Posted at 10:15am on Wednesday, August 1st, 2007

pls give me my tcp/ip to play warlords battlecry

Cat   

Posted at 7:21am on Thursday, August 2nd, 2007

I can has cheezeburger?

Wicked_Sunny   

Posted at 11:29pm on Thursday, August 2nd, 2007

It was really good..
I was really looking for such article to begin with socket programming.

May be I am on my way to develop My Chat application...
Be ready to test my version...

Mihir   

Posted at 1:18am on Saturday, August 11th, 2007

Thanks for this Simple introduction to Perl Sockets to give me a start..

kalyan   

Posted at 2:27am on Saturday, August 18th, 2007

it gud

but describe with starting commands to be used like

intilization of socket,termination of socket e.t.c.

andy   

Posted at 2:12pm on Tuesday, August 21st, 2007

any tips on "after sending the entire request switches to reading until the socket is closed."

I'd love to see this example extended to illustrate this!

matt   

Posted at 4:03pm on Thursday, August 23rd, 2007

I've been stuck on a problem with this regarding the read of the client filehandle...I want a server that periodically goes to check on all it's sockets with clients to see if any of them have messages...if so it'll service the sockets (all the lines of their communication) and then go back to it's normal business. The trick is I dont want to keep opening and closing new sockets and instead just keep them open and read from them when ->select tells me there's stuff there.

What seems to happen however is that my client sends a number of lines of info and the server prints through the first line and then the IO::Select->select then says none of the handles are readable...the can_read returns nothing and so does select. I then wait a bit (like 9 seconds or 3 loops of my "check on the sockets") and send another message from the client...suddenly all the stored up info floods out except again the last line...I then send 5 more lines and it again only writes out the 1st an then says no more...cycle repeating..

Anyway, here's my server code and the client code is beneath it...thanks for any observations!

matt

#!/usr/local/bin/perl


use IO::Socket;
use IO::Select;

my $server_socket = new IO::Socket::INET (
LocalHost => localhost,
LocalPort => 7070,
Proto => 'tcp',
Listen => 32768,
Reuse => 1,
timeout => 5,
);
die "Could not create socket: $!n" unless $server_socket;
print "created socket $server_socketn";

$Read_Handles_Object = new IO::Select(); # create handle set for reading
$Read_Handles_Object->add($server_socket); # add the main socket to the set

while (1) { # forever


while (1) { # keep in this loop as long as there is a readable filehandle..
# get the set of readable handles
#
my ($readable_handles) = IO::Select->select($Read_Handles_Object, undef, undef, 0);

if (! scalar @$readable_handles) {print "nothing left to read...n";last}

foreach $rh (@$readable_handles) {
#print "read handle found : '$rh'n";
# if it is the main socket then we have an incoming connection and
# we should accept() it and then add the new socket to the $Read_Handles_Object
if ($rh == $server_socket) {
# you get this when a new socket connection is formed..a new client starts and it assigns
# a socket filehandle to it.
#print " accept();
$Read_Handles_Object->add($client);
$ClientNumber{$client}=++$CLIENT_COUNT;
#print " %%% Adding '$client' to read setn";
}
# otherwise it is an ordinary socket and we should read and process the request
else {
#print " --this is an ordinary socket '$rh'n";

$buf = $rh->getline(); # grab a line .. it shouldnt block due to the select
if (! defined $buf) {
# the other end of the socket closed...close our end and remove
# it from the list of sockets to listen to..
print " |FROM CLIENT ".$ClientNumber{$rh}."| --socket closed--n";
$Read_Handles_Object->remove($rh);
close($rh);
last;
}
print " |FROM CLIENT ".$ClientNumber{$rh}."|$buf";
}
}
}


# after going through the sockets I'll get back to some other work
# .. I'll simulate that with a sleep 3 ..


print "sleeping...n";
sleep 3;
}



HERES THE CLIENT :

#!/usr/local/bin/perl


use IO::Socket;
my $sock = new IO::Socket::INET ( PeerAddr => 'palm',
PeerPort => '7070',
Proto => 'tcp',
);
die "Could not create socket: $!n" unless $sock;


while(1) {
print "Message : ";
chomp($message=);
print $sock "$messagen";
}

matt   

Posted at 4:04pm on Thursday, August 23rd, 2007

correction...palm on the client is the localhost...adjust that please ... issue still remains...

matt   

Posted at 12:12pm on Friday, August 24th, 2007

it seems that my paste into the entry box stripped out some stuff...like backslash n for a return drops the backslash..watch out for that..also in the client I get stdin with that chomp($message thing but it dropped the "open angle" STDIN "close angle" ...

note that to test this you can up the sleep to like 10 seconds and then while it's sleeping have the client send like 5 strings ... then when the server wakes up it prints out the first and then says no more read handles...then hit return again on the client and out it comes...if you dont like having a sleep this issue would also happen if the server took a few seconds to perform some action for one of the children while another was pumping messages into its socket..
thanks, Matt

baba   

Posted at 5:17am on Tuesday, August 28th, 2007

sorry i couldnt help you at present

shekar   

Posted at 3:42am on Monday, November 12th, 2007

anyone knows how to write smtp mail implementation in PERL , or graphical soket programing to implement SMTP please reply now

Shannon   

Posted at 8:05am on Friday, November 16th, 2007

Anyone can help on the following problem:

(Perl IO::Socket module)The client will prompt the user for two numbers and send them to the server. After server add the numbers and send back to client, THEN client will display the result to the user.

Richard   

Posted at 3:39am on Tuesday, November 20th, 2007

Hi,

The example on top is a one way communication. I would like to send back a message from the serber, to the client:
1) Client sends "Hello there!"
2) Server prints on the screen "Hello there!", and then replies the number of bytes received.
3) Client prints out 12 (the number of bytes sent), and then terminates.

Is there a quick way to do this, or do I have to set up another port for the answer?

Regards,
/Richard

krishna   

Posted at 3:57am on Tuesday, November 27th, 2007

use strict;
use Socket;

# use port 7890 as default
my $port = shift || 7890;
my $proto = getprotobyname('tcp');

# create a socket, make it reusable
socket(SERVER, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1) or die "setsock: $!";

# grab a port on this machine
my $paddr = sockaddr_in($port, INADDR_ANY);

# bind to a port, then listen
bind(SERVER, $paddr) or die "bind: $!";
listen(SERVER, SOMAXCONN) or die "listen: $!";
print "SERVER started on port $port n";

# accepting a connection
my $client_addr;
while ($client_addr = accept(CLIENT, SERVER))
{
# find out who connected
my ($client_port, $client_ip) = sockaddr_in($client_addr);
my $client_ipnum = inet_ntoa($client_ip);
my $client_host = gethostbyaddr($client_ip, AF_INET);
# print who has connected
# send them a message, close connection
print CLIENT "Smile from the servern";
print "got a connection from: $client_host"," [$client_ipnum] n";
close CLIENT;}

Pasini   

Posted at 3:29am on Thursday, November 29th, 2007

Hi, I am new to internet programming but I have some years with electronics, microcontrollers and windows apps.
My question is simple and I think PERL may be the right way to solve it. Please help me:
1) I want a socket server and a web/e-mail/ftp server in the same machine, to which I dont have direct access since it is my ISP machine in another city.
2) How do I create the socket server ? Is it a PERL module and this lines of code from other messages ? How do I install it and how do I run it (I cannot run it from command line !!!) ? Nobody will be able to type commands from command line to run it !
3) The client will be something like hyperterminal from windows (actually an equipment).
Can you suggest a book or tutorial that teaches me how to work with server sockets, install and run it ?
Thanks in advance,
Pasini

Sandy   

Posted at 11:29pm on Tuesday, December 4th, 2007

Very simple and easy to understand..Thanks buddy!

Allen Alex   

Posted at 2:37am on Thursday, December 13th, 2007

GREAT ARTICLE
thanks buddy...

Dale   

Posted at 11:08am on Thursday, December 13th, 2007

This script was a great help! Thanks!

gammy   

Posted at 5:13am on Tuesday, December 18th, 2007

I must say I cannot get this example working at all - I've been tinkering with it for about an hour now and it just doesn't work as explained at all. http://pastebin.ca/821913 shows my code(pretty identical to above)

gammy   

Posted at 8:32am on Tuesday, December 18th, 2007

Ah, I am but a fool! Solved it. Excellent!

james   

Posted at 12:38am on Sunday, December 30th, 2007

Nice article, easy to understand. Thanks!!

Ranjit   

Posted at 11:20am on Friday, January 18th, 2008

How do I incorporate variables into the script above. I got it working, but I am having trouble transferring variables.

Jack   

Posted at 11:56am on Tuesday, January 22nd, 2008

Many thanks. Just a question. How can the server sends a reply to the client?

steve   

Posted at 8:36pm on Tuesday, January 22nd, 2008

excellent... this little bit of code helped me create a simple remote admin script for video switching units with absolutely no previous experience with perl. thanks!

Paras   

Posted at 10:56am on Thursday, January 24th, 2008

Thanks a ton man.. it really helped me in implementing customized script for sending real time logs to central log server (syslog_ng).
Again, thanks a ton for it....

manohar   

Posted at 11:47am on Thursday, February 21st, 2008

can any one suggest with the perl scripts used in automation of SIP testing

Marko   

Posted at 7:29am on Saturday, February 23rd, 2008

Hello,
I am also looking for a perl script to handle SIP testing.

- The idea is to have a simple scrit (ex ua.pl) that sends "template files" as argument (ex: ua.pl template.txt).

- The ua.pl shall sends the data over udp to peer server ip address on port 5060 for instance.

- Template files are not part of the script but written by user .. copy/past from some call flows.

So will be happy if some one post a simple script that reads the file (template) and sends it to server.

ronie   

Posted at 4:58pm on Monday, February 25th, 2008

Hello,
I am new to perl and have been doing some reading. Can someone tell me how to call a script in another host? This article has really helped me, i have been able to create my client and server, but i need to know how to call a sript to do things for me while connecting to the server.
Thanks

Erwin   

Posted at 6:55am on Wednesday, February 27th, 2008

I just implemented the two scripts (server and client) and work fine the first time. While server is runnin in the background I run the client the first time and works, but the second time I run the client I get an error "could not create socket: Connection refuse" then I see the server teminating. Something missing on the code?

harry   

Posted at 2:02pm on Thursday, February 28th, 2008

Erwin, you need to put the $socket->accept() in a loop

Benjamin   

Posted at 1:22am on Tuesday, March 4th, 2008

Hello,

I'm just trying to find a possiblity to check if a specific port (e.g. 80) is listening unter Solaris. But tbh i'm very new to all of that and i thought that active probing (trying to establish a connection to the port, see if it works and cancel the connection if necessary) with a result of 0 or 1 would be best.
I found that article with google but tbh it doesn't help me that much :(

Cheers,
Benjamin

Anonymous   

Posted at 1:10pm on Thursday, March 6th, 2008

Harry,
Thanks, it works as designed. Now I'm looking for a similar client but for Windows, it would be great if done in VBS.
Thanks again.

niks   

Posted at 2:37am on Tuesday, March 25th, 2008

For all those who want to write back something to client, you can use the print statement.

e.g.
1 use IO::Socket;
2 my $sock = new IO::Socket::INET (
3 LocalHost => 'thekla',
4 LocalPort => '7070',
5 Proto => 'tcp',
6 Listen => 1,
7 Reuse => 1,
8 );
9 die "Could not create socket: $!n" unless $sock;
10 my $new_sock = $sock->accept();

At this step you can employ specific code to read something from client and then when its time to write something to client this is what you do:

print $new_sock "Here comes the response from server...n";

Thats it!.

Depending upon the requirement above code may get more complex, but this atleast gives you some idea.

--Niks.

dwight   

Posted at 2:05pm on Monday, March 31st, 2008

Could Anyone Help Me With This Socket Connection?

I'm attempting to tcp a microcontroller. I'm able to do it with vb from a laptop, but I want to communicate from a web page using Perl.

I need to send the characters "F5F0" to the micro controller at ipaddress 24.180.20.119 port 59004. The ipaddress (not real) is to my router and the port is the port of the micro controller. I'm trying this code, it does not reurn an error when udp is used, but returns an internal sever error when I change to tcp:

#!/usr/local/bin/perl -w
use strict;
use IO::Socket::INET;
my $sock = new IO::Socket::INET (
PeerAddr => '24.180.20.119',
PeerPort => '59004',
#Proto => 'tcp',
Proto => 'udp',
);
die "Could not create socket: $!n" unless $sock;
print $sock "F5F0";
close($sock);

print "Content-type: text/htmlnn";
print "Hi there!n";
exit;

The vb program that does work uses winsock like this:

If Winsock1.CtlState MSWinsockLib.StateConstants.sckClosed Then Winsock1.Close()
Winsock1.RemoteHost = IP_Address.Text
Winsock1.RemotePort = 59004
Winsock1.LocalPort = 0
Winsock1.Connect()
If Winsock1.CtlState = MSWinsockLib.StateConstants.sckConnected Then
If RadioButton6.Checked = True Then
Call Winsock1.SendData("F5F0")

endif

Lar   

Posted at 10:07pm on Wednesday, April 16th, 2008

hey everybody, everything looks good and easy, but being a bit defensive minded, can someone point me to resources about checking to make sure we don't get DOS'ed or similar?

Thanks!

Jay   

Posted at 12:04pm on Tuesday, April 22nd, 2008

Thanks a lot, its simple and easy in your demonstration. Great effort mate.

Nhung   

Posted at 6:52am on Wednesday, April 30th, 2008

In the beginning, I used your first program, but it did not work. I dont know why? I installed Apache and Perl on Windows xp? Is that a problem? Do I need to setup something with Perl and Apache to use socket?

bipul   

Posted at 10:23pm on Wednesday, April 30th, 2008

Great Article, well written.
Atleast some basic concepts got cleared.

kuji   

Posted at 11:18am on Tuesday, June 17th, 2008

I was wondering if there was a way to actually control the pins of the LPT port with a perl script(I more interested in the jetdirect 310).Can I have a basic sample script

Firehawk   

Posted at 12:22pm on Wednesday, July 2nd, 2008

I was able to setup the socket test however, I want it to print to a log file with a date and time stamp. Is there some place I can read on how to or does some have an example?

I basically want to update a log file with the entry and then roll the log daily.

#! /usr/bin/perl -w


use IO::Socket;
my $msg = "";
my $socket = IO::Socket::INET->new (
PeerAddr => 'localhost',
PeerPort => '4035',
Proto => 'tcp',
Type => SOCK_STREAM,
Blocking=> 0)
or die "Could not create socket: $!n";
print $socket "0006HI";
my $sock_addr = recv($socket,$msg,190,0);
if ($msg =~ /0190HI/) {
print "ISD Switch is upn";
print "response is $msgn";
}
close($socket);

KhinMyatMyatSoe   

Posted at 10:49pm on Wednesday, July 2nd, 2008

Reexplain this Website in words, no programming language.
This Website is very useful.

Thom   

Posted at 11:05pm on Wednesday, July 9th, 2008

Any idea on how you could call a servlet this way, writing a GET command?

Ashton   

Posted at 10:02am on Monday, August 18th, 2008

So my problem is this: I need a check to transfer FROM a linux box TO a windows box. It needs to send the command name and the flags to be used. I have successfully used this socket protocol to do so, but it dies every time it's done, which is a problem. I need it to be perpetual, like a web server. How do I do that?

Prashant   

Posted at 4:03am on Tuesday, August 19th, 2008

i want to read the data frn http port i jst simply want create log watever site hasbeen accesed. plzz help me out ASAP..

Bthoj   

Posted at 11:20am on Wednesday, August 20th, 2008

With the above codes... how do you make the client and server automatically scan for an open port to use? I also want to be able to have the client print out the port being used to the server and the server displays the port number?

Roland   

Posted at 1:39am on Friday, September 12th, 2008

Many thanks for this tutorial.

ram   

Posted at 11:17pm on Monday, September 15th, 2008

Thank you so much for the beautiful explanation of sockets
thank you so much

ANISH.H.DAS   

Posted at 5:47pm on Tuesday, September 23rd, 2008

Thank you so much for the beautiful explanation of sockets

Anjali   

Posted at 11:04pm on Thursday, September 25th, 2008

Can anybody tell me how to write sip programs using perl?

Navin   

Posted at 4:00pm on Thursday, October 2nd, 2008

Asthon..
use the below code to get the server up and running in background..

while( $new_sock = $sock->accept())
{
while() {
print $_;
}
}
close($sock);

Navin   

Posted at 4:02pm on Thursday, October 2nd, 2008

while( $new_sock = $sock->accept())
{
while()
{ print $_; }
}

Navin   

Posted at 4:05pm on Thursday, October 2nd, 2008

looks like .. need to use the escape char to print
angle brackets .. inside while should be ..
while()
{print $_; }

hell   

Posted at 4:08pm on Thursday, October 2nd, 2008

while(<$new_sock>)
{print $_; }

RRN   

Posted at 11:18pm on Monday, November 10th, 2008

can any one help me
i am not able to transfer message from one ip to another ip
here is the server
#################
#!/usr/bin/perl
use IO::Socket;

my $sock = new IO::Socket::INET (
LocalHost => 'localhost',
LocalPort => '7070',
Proto => 'tcp',
Listen => 1,
Reuse => 1,
Blocking=>1,
);
die "Could not create socket: $!n" unless $sock;
my $new_sock = $sock->accept();

while()
{
print $_;
}
close($sock);

..................
And here is the client
###########
#!/usr/bin/perl

use IO::Socket;
my $sock=new IO::Socket::INET (
PeerAddr=>'localhost',
PeerPort=>'7070',
Proto=>'tcp',
);
die"couldnot create a socket:$!n" unless $sock;

foreach my $i (1..5) {

print $sock"helloworldn";

}
close($sock);

RRN   

Posted at 2:15am on Friday, November 21st, 2008

how to block a perticular port using perl in TCP/IP networking

Thanos   

Posted at 5:22am on Wednesday, January 28th, 2009

I am trying to build a tcp/ip to serial redirect (both ways) for interfacing with an old control system. I've found somewhere on the net this script

http://www.jrbtech.com/2008/code/perl-a-tcp-daemon-written-for-perl.html

but does not seem to work as expected. Can anyone help please?

Dave Mathews   

Posted at 4:24pm on Sunday, February 8th, 2009

When I send large records from the Client to the Server and write them to a file the records get truncated. In C I had to have the server do multiple receives to get all the data from a single send on the client. How do I do this in Perl?

Kesh   

Posted at 1:54am on Tuesday, February 10th, 2009

Great article; thanks.

Minok   

Posted at 6:06pm on Thursday, February 12th, 2009

Now, can someone explain why, taking that very basic starting example, if I tweek it to try and create a udp datagram socket, the new fails?


my $sock = new IO::Socket::INET (
LocalHost => 'localhost',
LocalPort => '1217',
Proto => 'udp',
Listen => 1,
Reuse => 1,
Type => SOCK_DGRAM,
);

akshatha   

Posted at 9:29pm on Sunday, February 15th, 2009

i wanted to have a socket programming using SSH.can we have it?i have got to include a script in that which includes multiple IP adresses.

akshatha   

Posted at 9:30pm on Sunday, February 15th, 2009

i wanted to have a socket programming using SSH.can we have it?i have got to include a script in that which includes multiple IP adresses.

Phanleson   

Posted at 10:22pm on Friday, February 27th, 2009

Oh, this tutorial is very basic for newbie, i am a java developer and i have learned perl few year ago.
Thank you for this tutorial

SS   

Posted at 2:33am on Monday, March 2nd, 2009

Develop a application over UDP
Client sends array X and Y to Proxy Server.
Proxy Server receives the two arrays from Client and sends to Server1, Server2 and Server3.
Server1 receives the two arrays from Proxy Server and calculate sum of number and send result to Proxy Server and also print the result on its standard output.
Server2 receives the two arrays from Proxy Server and calculate sum of square and send result to Proxy Server and also prints the result on its standard output.
Server3 receives the two arrays from Proxy Server and calculate sum of cube and send result to Proxy Server and also prints the result on its standard output.
After receiving result from Servers, Proxy Server sends all result to Client.
Proxy Server receiving all results from Servers, it sends to Client.

priya   

Posted at 9:15pm on Monday, April 20th, 2009

i want info @ 'select' structure using tcp for messenger

Naresh   

Posted at 2:43am on Monday, June 15th, 2009

I need to pass the parameters in url and get back the result to the client in url

Please suggest.

Thanks

damelep   

Posted at 11:50am on Wednesday, June 24th, 2009

Nice work dude ! Excellent Code !!!

Amy   

Posted at 10:42am on Wednesday, September 9th, 2009

An awesome tutorial with great code... works perfectly! Thank you!

Anonymous   

Posted at 12:15am on Friday, November 20th, 2009

the above client program is not working on my windows xp..... pls help me..

Mike Lacey   

Posted at 3:30am on Tuesday, December 15th, 2009

Good article, thank you.

You may not be aware that "Network Programming in Perl" at http://home.t-online.de/home/wahls/perlnet.html does not seem to be available anymore.

Regards,

Mike

Phil   

Posted at 7:44am on Wednesday, January 13th, 2010

first Comment in 2010!

Hakim   

Posted at 9:13pm on Thursday, January 21st, 2010

I have following perl script whihc runs well on my machine but my other machine is configured in a way where it has to go through a proxy before connecting to those servers. The Proxy IP is "aa.bb.cc.dd" and port is "abcd". How do i script in perl to connect to the servers through proxy servers? Please help!!!

use Net::Telnet;

$username=hakim;
$password=pwd;


@server=("ABC","XYZ");
foreach $server (@server){
$telnet = new Net::Telnet (Timeout=>1000,Errmode=>'die',Cmd_remove_mode=>'auto');
$telnet->open($server);
$telnet->waitfor('/login: $/i');
$telnet->print($username);
$telnet->waitfor('/password: $/i');
$telnet->print($password);
$telnet->waitfor('/$ $/i');
$telnet->cmd("cd $HOME");
$telnet->print('find /Path -name "file*" -print 2>/dev/null | xargs egrep -i "HOST>20100113 $HOME/searchfile');
$telnet->waitfor('/$ $/i');
$telnet->close;
}

SydneyBoy   

Posted at 8:53pm on Wednesday, March 17th, 2010

Can someone help me for a perl script to limit the internet download size in a LAN based on week

Tekle   

Posted at 7:06pm on Thursday, March 25th, 2010

this is a very good introduction.thank you

Dale   

Posted at 10:21am on Thursday, April 1st, 2010

How does the client recv a pass back from the Server?
I can send to the server no problem and have the server print what I send but if the server send a message back I can seem to get it.

Navnit   

Posted at 7:39am on Thursday, April 8th, 2010

Help me please...

The following is the out from my terminal when i run the perl script. Can anybody help me? Thanks in advance...

============================================================
Terminal snapshot :
============================================================
[koha@localhost ~]$ cat receiver.pl
use IO::Socket;
my $sock = new IO::Socket::INET (
LocalHost => 'localhost',
LocalPort => '7070',
Proto => 'tcp',
Listen => 1,
Reuse => 1,
);

die "Could not create socket: $!n" unless $sock;

my $new_sock = $sock->accept();

while() {
print $_;
}

close($sock);[koha@localhost ~]$ cat sender.pl
use IO::Socket;

my $sock = new IO::Socket::INET (

PeerAddr => 'localhost',
PeerPort => '7070',
Proto => 'tcp',
);

die "Could not create socket: $!n" unless $sock;
print $sock "Hello there!n";
close($sock);[koha@localhost ~]$ perl receiver.pl
Could not create socket: Invalid argument
[koha@localhost ~]$
============================================================

Navnit   

Posted at 7:43am on Thursday, April 8th, 2010

Help me please...

The following is the out from my terminal when i run the perl script. Can anybody help me? Thanks in advance...

============================================================
Terminal snapshot :
============================================================
[koha@localhost ~]$ cat receiver.pl
use IO::Socket;
my $sock = new IO::Socket::INET (
LocalHost => 'localhost',
LocalPort => '7070',
Proto => 'tcp',
Listen => 1,
Reuse => 1,
);

die "Could not create socket: $!n" unless $sock;

my $new_sock = $sock->accept();

while() {
print $_;
}

close($sock);

[koha@localhost ~]$ cat sender.pl
use IO::Socket;

my $sock = new IO::Socket::INET (

PeerAddr => 'localhost',
PeerPort => '7070',
Proto => 'tcp',
);

die "Could not create socket: $!n" unless $sock;
print $sock "Hello there!n";
close($sock);

[koha@localhost ~]$ perl receiver.pl
Could not create socket: Invalid argument

[koha@localhost ~]$
============================================================

uturner   

Posted at 12:33pm on Tuesday, May 4th, 2010

class example.........encoded with compiled theory.....

Bilal   

Posted at 7:46am on Wednesday, May 5th, 2010

I have a perl script for unix which uses a socket to read data from gsm modem connected to com port.I need to convert it to windows.I think most of the script is going to be same except the line which establishes the socket connection.
Could someone please help me to know which lines I should change so that it will work on windows.
Here is the script
#!/usr/bin/perl -w

# TRG: Perl script to exercise GSM card through a set of diagnostic commands
# The results from each command are sent back to the browser client
# Accesses the GSM card via gsmd socket (for sharing)

use strict;
use IO::Socket::UNIX;
use Term::ReadKey;
use IO::Select;
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);

# Keep Apache happy with the content
print "Content-type: text/htmlnn";

# Open the socket connection to GSMD
my $sock = new IO::Socket::UNIX (Type => SOCK_STREAM,
Peer => '/home/glucose/gsm/gsmd_sock',
Timeout => 60) || die "Couldn't establish socket: $!";
$! = 1;
my $s = IO::Select->new();
$s->add($sock);
$sock->autoflush(1);
ReadMode 4;

# Display suitable HTML headers and send a series of commands

#print "GSM Card Diagnosticsn";
sendcommand($s,$sock,"at+cerrn",'Last Error Message','');
sendcommand($s,$sock,"at+cscs="GSM"n",'Select ASCII output','');

print "GSM Card Detailsn";
sendcommand($s,$sock,"at+cgmin",'Manufacturer Indentification','');
sendcommand($s,$sock,"at+cgmmn",'Model Identification','');
sendcommand($s,$sock,"at+cgmrn",'Revision','');
sendcommand($s,$sock,"at+cgsnn",'Serial Number','');

print "Subscriber Identificationn";
sendcommand($s,$sock,"at+cimin",'International Mobile Subscriber Identity','');
sendcommand($s,$sock,"at+ccidn",'SIM card ID','');
sendcommand($s,$sock,"at+gcapn",'List of capabilities','');
sendcommand($s,$sock,"at+cnumn",'Subscriber number','');

printf "Current Statusn";
sendcommand($s,$sock,"at+cpasn",'Status','(0=ready, 1=unavailable, 2=unknowm, 3=ringing, 4=call-in-progress, 5=asleep');
sendcommand($s,$sock,"at+cfun?n",'Functions','(power,stk)');
sendcommand($s,$sock,"at+cmer?n",'Term event reporting','(mode,kpd,disp,ind,bfr)');
sendcommand($s,$sock,"at+cclk?n",'clock','(yy/mm/dd hh:mm:ss)');
sendcommand($s,$sock,"at+csqn", 'Signal Strength','(rssi,ber)');
sendcommand($s,$sock,"at+creg?n",'Network registration ','(n,stat,location,cellident) stat=1(home) ');

printf "SMSn";
sendcommand($s,$sock,"at+cnmi?n",'New Message Indication');
sendcommand($s,$sock,"at+csca?n",'Service centre address');
sendcommand($s,$sock,"at+cmgln",'List messages');

sendcommand($s,$sock,"at+cscs="HEX"n",'Hex output','');

# Close the socket connection and were done
$sock->close();
ReadMode 0;
exit;


# -----------------------------------------------------------------
# Subroutine to send a command to the diagnostic socket and print the response
sub sendcommand {
my $s = shift;
my $sock = shift;
my $cmd = shift;
my $desc = shift;
my $comment = shift;
my $rtn = '';
#print description
print "$desc ";
#send the command
$sock->syswrite($cmd);
sleep 1;
# read the response and print
while ($s->can_read(0))
{
$sock->sysread($rtn,1);
print $rtn;
}
print "n $commentn";
return;
}

machchakumar   

Posted at 12:28am on Wednesday, June 23rd, 2010

it is usfull for me because read about more for tcp/ip ,socket,ect

Harpreet   

Posted at 9:45pm on Thursday, July 29th, 2010

Thanks,

created a script using the above...
http://rowsandcolumns.blogspot.com/2010/07/perl-how-to-create-tcp-socket.html

thangavel   

Posted at 4:24am on Wednesday, October 20th, 2010

super thought

lordcountley@gmail.com   

Posted at 5:09am on Sunday, November 7th, 2010

very good

Super_carotte   

Posted at 8:35am on Thursday, November 25th, 2010

To Bilal:
have you tried this line at the end of your code:
$SIG{CHLD} = 'IGNORE';

Craig   

Posted at 9:03pm on Sunday, December 19th, 2010

I have struggled with writing a stand alone SMTP Mail Server in Perl for years. NETSMTP doesn't cut it for me and I've bought fancy junk that doesn't give me the control or simplicity I wanted. Your script did. I am not done yet - my GNUSMTP.PL sends messages but the message body is empty (?hmmmm) - but for the first time ever I can actually get a message sent from a file to yahoo or gmail and that's a first step.

Craig   

Posted at 9:04pm on Sunday, December 19th, 2010

I have struggled with writing a stand alone SMTP Mail Server in Perl for years. NETSMTP doesn't cut it for me and I've bought fancy junk that doesn't give me the control or simplicity I wanted. Your script did. I am not done yet - my GNUSMTP.PL sends messages but the message body is empty (?hmmmm) - but for the first time ever I can actually get a message sent from a file to yahoo or gmail and that's a first step.

Ijalba   

Posted at 8:41am on Thursday, January 13th, 2011

First comment of 2011, hehehe. I get an error on the 1st script:

"use" not allowed in expression at opensocket.pl line 21, at end of line syntax error at opensocket.pl line 21, near "use IO::Socket"

Ijalba   

Posted at 9:41am on Thursday, January 13th, 2011

Corrected. It works FINE!!!! very good example. It will aid me greatly to test connections properly without having to depend on external applications, or in the network guys...

Natali   

Posted at 5:11am on Monday, January 31st, 2011

Hello friends,this is a nice site and I wanted to post a note to let you know, good job! Thanks
Best regards, Natali, CEO of os x iscsi initiator

Natali   

Posted at 5:13am on Monday, January 31st, 2011

Hello friends,this is a nice site and I wanted to post a note to let you know, good job! Thanks
Best regards, Natali, CEO of os x iscsi initiator

Gururaj CM   

Posted at 9:52pm on Monday, February 14th, 2011

Thanks really it was a great material

rocko   

Posted at 6:37pm on Sunday, March 27th, 2011

Can localhost =>"" be any PC's IP address?
I have 2 PC's on my home network and would like to try this script on them.
But I keep getting:"Cannot create socket, Cannot assign address", when ever I put anything other then the localhost address.

Louis Vuitton   

Posted at 2:25am on Wednesday, March 30th, 2011

I just required some information and was searching on Google for it. I visited each page that came on first page and didn

t got any relevant result then I thought to check out the second one and got your blog. This is what I wanted!

Ankur   

Posted at 12:13am on Thursday, April 14th, 2011

Is there any way we can do the client server communication using MAC address instead of IP address. i.e. using LLC protocol instead of TCP/UDP

petros   

Posted at 11:08am on Sunday, May 8th, 2011

are you from Cyrpus or greecy? Awesome article really helpfull :D

Ouissem   

Posted at 4:01am on Friday, May 20th, 2011

Thanks from Paris

YAK3   

Posted at 8:56am on Tuesday, May 31st, 2011

This article helps me!! thanks!! :)

Lifestyle Sucker   

Posted at 12:02am on Friday, June 10th, 2011

I Hate you ALL! :D
Bloody bastards :D

Lifestyle Sucker   

Posted at 12:03am on Friday, June 10th, 2011

I Hate you ALL! :D
Bloody bastards :D

Long Dieter   

Posted at 12:12am on Friday, June 10th, 2011

Hey guys, i like this articles a lot.
hope somebody wants to meet me privat and talk about all these things.
My Lange Lanze can put inside her/him :D

Long Dieter   

Posted at 12:12am on Friday, June 10th, 2011

Hey guys, i like this articles a lot.
hope somebody wants to meet me privat and talk about all these things.
My Lange Lanze can put inside her/him :D

BangCOCK   

Posted at 12:21am on Friday, June 10th, 2011

Hey guys.

I want to feel your Lange Lanze inside me.

Xhesi   

Posted at 6:56pm on Friday, June 24th, 2011

Great for beginners!
Thanks a lot! :)

Dallas Home Security   

Posted at 1:23am on Wednesday, June 29th, 2011

Thank you so significantly for your personal decent suggestion.I am going to give it a have a go with.
Are you able to inform me the identify of one's theme?
Dallas Alarm Companies

Suresh   

Posted at 11:29pm on Tuesday, July 5th, 2011

Good to practice

shan singh   

Posted at 10:32am on Tuesday, September 27th, 2011

i cannot create a socket form caller side. please help soon

shan singh   

Posted at 10:35am on Tuesday, September 27th, 2011

i cannot create a socket form caller side. please help soon

Knox30Lou   

Posted at 3:36pm on Friday, September 30th, 2011

Different people in every country get the home loans from various banks, because this is simple and comfortable.

Charles   

Posted at 11:10pm on Tuesday, October 4th, 2011

Having an issue with sockets. I connect to the server with my client, then send a request and receive a response. I'm then parsing the response with XML::XPath. This works perfectly fine the first time through. However, if I send another transaction with the same socket and receive another response, XML::XPath cannot parse the response, even though it just appears to be a regular xml string. If I close the socket and open a new one and do it all over again, it works fine. But I don't want to be opening and closing the socket each time, I want to make all of my transactions on the open socket and then close when I'm done. I've set autoflush to 1, but that made no difference. What am I missing?

Charles

ASHLEY32Morrison   

Posted at 3:10pm on Friday, October 7th, 2011

Set your own life more simple take the credit loans and everything you want.

Home Security   

Posted at 9:40am on Thursday, November 3rd, 2011

I want to show my admiration of your writing skill and ability to make audience, browse the whole thing to the end. I'd really like to read more of your blogs and to talk about my views with you. I'll be your frequent website visitor, thats for sure.

MicheleMcfarland27   

Posted at 2:17am on Tuesday, November 29th, 2011

The loan suppose to be useful for guys, which are willing to start their business. As a fact, it's comfortable to get a student loan.

Parag Kamble   

Posted at 11:18pm on Monday, December 5th, 2011

How to transfer File Using Socket?

Imran Saad   

Posted at 6:27am on Monday, December 12th, 2011

A socket can be created with a SIP server on port 5060 but what protocol should be used to supply username and password to get registered to the SIP server . NAT has to be disabled for SIP to work well because of address mismatch issues . A perl script to check if client is registered to SIP Server which means check registration status of a particular user/password combination .,

Anonymous   

Posted at 5:12am on Tuesday, December 27th, 2011

Really appreciate this wonderful post that you have provided for us.Great site and a great topic as well i really get amazed to read this.
gps navigator

Derlierprossy   

Posted at 10:28pm on Tuesday, December 27th, 2011

You post this blog about stock.I wish there were additional websites like it. At any rate, I thought it was about time I posted.Im not that much of a reader to be candid but your websites pretty first-rate, keep it up as I will bookmark ready for my next read.
Desktop computer

therulerofchina   

Posted at 1:52pm on Tuesday, February 21st, 2012

is it possible to use this to execute commands as well or is it just talk? i tried replacing print with

system ($^X, $_) but that didn't work....

otherwise a brilliant tutorial!

Nima   

Posted at 1:01am on Tuesday, March 6th, 2012

Excellent job! You really made it easy for us to understand the concept of socket...Thank you.

Anonymous   

Posted at 9:37pm on Wednesday, March 14th, 2012

thanks sir G ur notes is well

Richard Braganza   

Posted at 5:57am on Tuesday, April 17th, 2012

Thanks for this but should not Listen should close $newsock and not $sock
R

SEO Services   

Posted at 10:35pm on Sunday, April 29th, 2012

I am very interested for this post. Its really give me lots of pleasure. I choose this article very much. So lots of thanks for this post.

SEO Services

davidvorner   

Posted at 10:48pm on Monday, April 30th, 2012

i was looking for these information after a long time!
copywriting services uk seo services uk Content writing service

guerPlemErura   

Posted at 1:58pm on Thursday, July 26th, 2012

°t¥kˡΤ̨gͬˆƤ롣ע⤷ʤФʤʤU䤬rϡäȤΕrꌏΡgOܿgҡOˇgҡܿgҤϡФΌߤơ⤷`ƥȤ http://www.coachnihonn.com/ - `Хå ƷA˴ССϺΤǤˤеҊϡ줬פĤӤ衣顢¤UQϤä߳줿ΤǤ狼ʤƤ⡢Фܤ

Senad   

Posted at 11:33pm on Monday, August 20th, 2012

There really isn't a huge avadntage to using sockets. My tests with a clean install of WordPress 3.0 with no plugins and running Twentyten showed negligible speed improvements. Using localhost I averaged 0.2103 seconds for 15 queries (over 20 tests) and with sockets I averaged 0.20965 seconds for 15 queries (over 20 tests). This is generally just required due to server configs. Why all of the sudden users are needing this? I couldn't say; maybe it is just the latest MySQL configuration craze ;)

ityfim   

Posted at 8:55pm on Tuesday, August 21st, 2012

7Jnhrj jjdnhqadjifq

ckfznpkqhqy   

Posted at 3:15pm on Thursday, August 23rd, 2012

hTzvxV dbioznjxhnte

wxbxkgq   

Posted at 10:36pm on Saturday, August 25th, 2012

Martial arts isabel marant sneakers fall 2013 are improvised version of sashes. Therefore the kippys Beltreveled you by lending you greatest quality isabel marant sneakers how much of your option which will delineate you distinguish from the crowed. Aside from this, isabel marant cowboy boots is also used as an expression of themselves. Such briefcases and satchels range in size and shape from the s

ManyNeday   

Posted at 2:37pm on Friday, November 16th, 2012

Installation {geodeta|geodezyjne|moda dla puszystych|moda|odzież|ubrania|xxl|wesele|sale weselne|wesela be expeditious for|for|be incumbent on|be advisable for|be advantageous to} uninterruptible {capability faculty|skills|knack|ability|facility impedimenta|paraphernalia|goods|gearbox|raiment} or {Vacillate|Change|Oscillations|Changes|Inconstancy} systems is {combine|three

RAVI GODARA   

Posted at 10:52am on Sunday, January 13th, 2013

Great dear ...... thank u very much....

RAVI GODARA   

Posted at 10:54am on Sunday, January 13th, 2013

Great dear ...... thank u very much....

Shaheed   

Posted at 12:00am on Tuesday, January 22nd, 2013

Its working thank you...

chotu   

Posted at 1:24am on Wednesday, March 13th, 2013

what is it????????????????????

jimmy   

Posted at 1:25am on Wednesday, March 13th, 2013

even i dont know? which gender you are?????????

gopal   

Posted at 4:02am on Monday, August 26th, 2013

I want connect remote server and local compute .But the client and severer program work on local computer only not work different machine .Its show o below error


cannot connect to the server A connection attempt failed because the connected p
arty did not properly respond after a period of time, or established connection
failed because connected host has failed to respond.


Can I any change server

yourMum   

Posted at 7:52am on Wednesday, November 20th, 2013

Aint nobody

Gao Oufan   

Posted at 4:07am on Sunday, February 23rd, 2014

Can it work as a regular CGI script as well? (Each CGI will handle only ONE single connection then)

Networkingtraining   

Posted at 4:15am on Tuesday, May 20th, 2014

Great website........

Networking training in chandigarh

Adrian   

Posted at 6:59pm on Monday, June 23rd, 2014

It is very great article ~~~

Wayne   

Posted at 8:16am on Tuesday, October 21st, 2014

Do you have a new link for Network Programming in Perl? That one is no longer available.
Thanks
Wayne

Comments to date: 153.

Like it? Share it!

Suggested Reading

Perl Cookbook The Perl Cookbook is full of quick solutions to everyday programming problems in perl with explanations and tips easy to understand even for beginners, but also frequently useful even to more experienced programmers. The code is clear and straightforward and the topics covered as well-thought and correspond to real world examples, so frequently you can literally copy code snippets from the book and fit them in your program. It is a nice complement for the Camel Book on your bookshelf.