int socket(int family, int type, int protocol); 该接口创建一个套接字
family指定协议族(通常是AF_INET);type参数指定socket的类型:SOCK_STREAM、SOCK_DGRAM、SOCK_RAW;protocol通常赋值"0"。
int bind(int sockfd, struct sockaddr *my_addr, int addrlen); 将套接字绑定到IP地址和端口
struct sockaddr_in
{
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
{
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
一个绑定的实例:
struct sockaddr_in saddr;
memset((void *)&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(8888);端口号要大于1024
saddr.sin_addr.s_addr = htonl(INADDR_ANY); 绑定到本地IP
//saddr.sin_addr.s_addr = inet_addr("192.168.22.5"); 绑定固定IP
bind(ListenSocket,(struct sockaddr *)&saddr,sizeof(saddr));
memset((void *)&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(8888);端口号要大于1024
saddr.sin_addr.s_addr = htonl(INADDR_ANY); 绑定到本地IP
//saddr.sin_addr.s_addr = inet_addr("192.168.22.5"); 绑定固定IP
bind(ListenSocket,(struct sockaddr *)&saddr,sizeof(saddr));
int listen(int sockfd, int backlog);
sockfd是socket系统调用返回的服务器端socket描述符;backlog指定在请求队列中允许的最大请求数
int accept(int sockfd, struct sockaddr *addr, int *addrlen);
sockfd是被监听的服务器socket描述符,addr通常是一个指向sockaddr_in变量的指针,该变量用来存放提出连接请求的客户端地址
connect()函数用来与远端服务器建立一个TCP连接其函数原型为:
int connect(int sockfd, struct sockaddr *serv_addr, int addrlen);
int connect(int sockfd, struct sockaddr *serv_addr, int addrlen);
int send(int sockfd, const void *msg, int len, int flags);
int recv(int sockfd,void *buf,int len,unsigned int flags);
int sendto(int sockfd, const void *msg,int len,unsigned int flags,const struct sockaddr *to,int tolen);用于面向非连接socket(SOCK_DGRAM/SOCK_RAW)上进行数据传输
int recvfrom(int sockfd,void *buf,int len,unsigned int flags,struct sockaddr *from,int *fromlen);
close(sockfd); close()是对套接字的操作,关闭后进程不能在访问这个套接字。
IP、DNS等相关函数
in_addr_t inet_addr(const char * strptr);将字符串IP地址转换为IPv4地址结构in_addr值
char * inet_ntoa(struct in_addr * addrptr);将IPv4地址结构in_addr值转换为字符串IP
struct hostent *gethostbyname(const char *name); 域名和IP地址的转换: