Linux Socket Programming by Example-第七章 TCP通信
/etc/services 定义服务与(ip、port)的关系
/etc/protocols 定义协议与port关系
cat /etc/services | less
tcpmux 1/tcp # TCP port service multiplexer
echo 7/tcp
echo 7/udp
discard 9/tcp sink null
discard 9/udp sink null
systat 11/tcp users
daytime 13/tcp
daytime 13/udp
netstat 15/tcp
qotd 17/tcp quote
msp 18/tcp # message send protocol
msp 18/udp
chargen 19/tcp ttytst source
chargen 19/udp ttytst source
cat /etc/services | less
ip 0 IP # internet protocol, pseudo protocol number
#hopopt 0 HOPOPT # IPv6 Hop-by-Hop Option [RFC1883]
icmp 1 ICMP # internet control message protocol
igmp 2 IGMP # Internet Group Management
ggp 3 GGP # gateway-gateway protocol
ipencap 4 IP-ENCAP # IP encapsulated in IP (officially ``IP‘‘)
st 5 ST # ST datagram mode
tcp 6 TCP # transmission control protocol
egp 8 EGP # exterior gateway protocol
igp 9 IGP # any private interior gateway (Cisco)
pup 12 PUP # PARC universal packet protocol
udp 17 UDP # user datagram protocol
hmp 20 HMP # host monitoring protocol
xns-idp 22 XNS-IDP # Xerox NS IDP
rdp 27 RDP # "reliable datagram" protocol
为了操作这2个文件,Linux系统提供了以下接口:
#include <netdb.h>
struct servent {
char *s_name; /* official service name */
char **s_aliases; /* alias list */
int s_port; /* port number */
char *s_proto; /* protocol to use */
}
struct servent *getservent(void);
struct servent *getservbyname(const char *name, const char *proto);
struct servent *getservbyport(int port, const char *proto);
void setservent(int stayopen);
void endservent(void);
struct protoent {
char *p_name; /* official protocol name */
char **p_aliases; /* alias list */
int p_proto; /* protocol number */
}
struct protoent *getprotoent(void);
struct protoent *getprotobyname(const char *name);
struct protoent *getprotobynumber(int proto);
void setprotoent(int stayopen);
void endprotoent(void);
需要注意的是:
1> getservent与getprotoent均只返回一个一条记录,需要反复迭代调用
才能遍历所有记录。
2> s_port为网络Endian,需要调用 ntohs转化为本地Endian
3> 别名是一个list记录,需要迭代访问
Linux还有一个与Port相关的守护进程inetd.
先查看是否运行:
ps aux | grep inetd
如没有安装,ubuntu下可以输入下面命令安装
sudo apt-get install openbsd-inetd
安装后,可以cat /etc/inetd.conf 查看其默认配置。
基本格式:
<service_name> <sock_type> <proto> <flags> <user> <server_path> <args>
inetd常驻系统,随时监听各个port来的connet请求,并自动调用
相关服务程序.
下面写一个简单程序测试下.
Step1: 修改/etc/inetd.conf,添加一条记录
showfilelist stream tcp nowait root /opt/showfilelist.sh
Step2: 在/opt下构建showfilelist.sh, 并设置权限777 (sudo chmod 777 showfilelist.sh)
#!/bin/sh
Step3: 修改/etc/services, 添加一条记录 (注意,需要看12345是否被使用)
showfilelist 12345/tcp #just a test
最后,使用telnet测试
输入sudo telnet localhost 12345
结果如下:
Trying 127.0.0.1...
Connected to localhost.
Escape character is ‘^]‘.
Just a Test, means Nothing!!!
Connection closed by foreign host.
Linux Socket Programming by Example-第七章 TCP通信,古老的榕树,5-wow.com
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。