Linux系统知识(十一)-Ubuntu使用TCP/UDP并限制最大连接数

一、Ubuntu使用TCP

1、使用TCP的命令:

/dev/[tcp|upd]/host/port;例如::cat

2、查看当前监听的端口

-bash: connect: 拒绝连接

-bash:/dev/[tcp|upd]/host/port: 拒绝连接

例:

-bash: connect: Connection refused

-bash: /dev/tcp/127.0.0.1/223: Connection refused

3、ls -l /proc/self/fd/ # 列出当前进程正在使用的文件描述符有哪些

4、打开TCP通道

下面这段代码:我们输入‘exec 8<>/dev/tcp/127.0.0.1/22’

root1@zserver:~$ exec 8<>/dev/tcp/127.0.0.1/22

root1@zserver:~$ ls -l /proc/self/fd/

total 0

lrwx------ 1 root1 root1 64 Jan 25 08:14 0 -> /dev/pts/0

lrwx------ 1 root1 root1 64 Jan 25 08:14 1 -> /dev/pts/0

lrwx------ 1 root1 root1 64 Jan 25 08:14 2 -> /dev/pts/0

lr-x------ 1 root1 root1 64 Jan 25 08:14 3 -> /proc/1883/fd

lrwx------ 1 root1 root1 64 Jan 25 08:14 8 -> 'socket:[30628]'

root1@zserver:~$

注:第8行,文件描述符8,表示打开一个socket通讯通道,这个是一个可以读写socket通道,因为用:"<>"打开。结果提示返回的通道为[30628]。

5、关闭TCP通道

exec 8>&- #关闭通道

root1@zserver:~$ exec 8>&

-bash: syntax error near unexpected token `newline'

root1@zserver:~$ exec 8>&-

root1@zserver:~$ ls -l /proc/self/fd/

total 0

lrwx------ 1 root1 root1 64 Jan 25 08:36 0 -> /dev/pts/0

lrwx------ 1 root1 root1 64 Jan 25 08:36 1 -> /dev/pts/0

lrwx------ 1 root1 root1 64 Jan 25 08:36 2 -> /dev/pts/0

lr-x------ 1 root1 root1 64 Jan 25 08:36 3 -> /proc/1928/fd

root1@zserver:~$

二、限制最大连接数

1、限制TCP最大连接数

1)改动前:ulimit -n=1024(每个进程能打开的文件描述符个数为1024)

2)改动:/etc/security/limits.conf添加一下内容:

1 * soft nofile 102400 2 * hard nofile 102400

3)改动后:ulimit -n变为102400(可以跑102400个)

2、端口地址范围限制(未达到想要的效果)

由于端口地址是16位,所以,就算把这个端口地址范围修改为1024--65535,也最多能开启64521个连接,而我现在只有一台虚拟机作为客户端,所以想要实现10万连接是不可能了,但是通过这次测试,也让我搞明白了,到底哪些参数会限制连接的上限。