最近在弄多网卡测试。本来以为很简单。不过还是费了一些力气找文档。集中记录一下。
1使用socket模块,绑定本地地址
#!/usr/bin/perl -w # tcp_socket_cli.pl use strict; use Socket; my $addr = $ARGV[0] || '220.181.x.x'; my $port = $ARGV[1] || '80'; my $dest = sockaddr_in($port,inet_aton($addr)); my $localaddr_port = sockaddr_in(0,inet_aton('192.168.1.8')); my $buf = undef; socket(SOCK,PF_INET,SOCK_STREAM,6) or die "Can't create socket: $!"; bind(SOCK,$localaddr_port) or die "Can't bind socket: $!"; connect(SOCK,$dest) or die "Can't connect: $!"; close SOCK;
2.使用io:socket:inet模块,绑定本地地址
#!/bin/env perl use strict ; use IO::Socket qw(:DEFAULT :crlf); use Time::HiRes qw(time); use Time::Local; my $sock = IO::Socket::INET->new(PeerAddr => '220.181.x.x',PeerPort => 'http(80)',LocalAddr => '192.168.1.8',Timeout => 2,Proto => 'tcp'); if($sock) { my $tcpsec2=time; Debug("TCP delay is $time\n",0); } else { Debug("Socket test Failed: $!\n",0); }
3.使用socket模块,绑定interface
#!/usr/bin/perl -w # tcp_socket_cli.pl use strict; use Socket; my $addr = $ARGV[0] || '220.181.x.x'; my $port = $ARGV[1] || '80'; my $dest = sockaddr_in($port,6) or die "Can't create socket: $!"; # SO_BINDTODEVICE = 25,bind to device eth8 setsockopt(SOCK,SOL_SOCKET,25,pack("Z*","eth2")); #bind(SOCK,$dest) or die "Can't connect: $!"; close SOCK;
4.使用io:socket:inet模块,绑定interface
#!/bin/env perl use strict ; #use socket qw(:DEFAULT :crlf); use IO::Socket qw(:DEFAULT :crlf); use Time::HiRes qw(time); use Time::Local; my $sock = IO::Socket::INET->new( Timeout => 2,Proto => 'tcp'); $sock-> sockopt( 25,"eth2")) ; my $tcpsec1=time; my $dest = sockaddr_in(80,inet_aton('220.181.x.x')); my $result=$sock->connect($dest);
最后注意一点
绑定ip和绑定网卡的效果是不同的(感觉server一般需要绑定ip,client一般需要绑定网卡?)
绑定网卡需要root权限
目前还没有好办法让perl可以获得root权限。(suid似乎是不行的,记得是linux的安全限制)
变通的办法是expect+sudo.不过太麻烦,不如直接用root跑了。
本方式只适用linux,sun和hp不行。其他未试过。