全部博文(146)
分类: LINUX
2008-02-01 12:01:20
socket编程常用函数
struct sockadd {
unsigned short sa_family;
char sa_data[14];
}
用于bind, connect, recvfrom, sendto
struct sockaddr_in {
short int sin_family; //AF_INET
unsigned short int sin_port; //网络字节顺序
struct in_addr sin_addr; //struct in_addr { unsigned long s_addr; }
unsigned char sin_zero[8];
}
sample:
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(3490);
sa.sin_addr.s_addr = inet_addr(”132.241.5.10″);
baero(&(sa.sin_zero),8);
转换函数:
unsigned long inet_addr(const char *cp);
char* inet_ntoa(strct in_addr in);
字节顺序转换:
htons()——-Host to network short
htonl()——–Host to network long
ntohs()——-Network to host short
ntohl()——–Network to host long
取得本地主机名
int gethostname (char *hostname, size_t size);
取得本地信息
int getsockname(int sockfd, struct sockaddr* addr, int * addrlen);
例如:
struct sockaddr_in sa;
int len=sizeof(sa);
getpeername(sockfd, (struct sockaddr*)&sa, &len);
printf(”local IP:%s”, inet_ntoa(sa.sin_addr.s_addr));
获得DNS信息
struct hostent * gethostbyname(const char* name);
struct hostent* gethostbyaddr(const char* addr, int len, int type);
读取或改变socker属性
int getsockopt(int sockfd, int level, int name, char* value, int* optlen);
int setsockopt(…….);
对于socket编程:level一般为SOL_SOCKET
常用:
SO_RCVTIMEO, SO_SNDTIMEO
SO_SNDBUF, SO_RCVBUF: buffer size
…..
网络连接
int socker(int domain, int type, int protocol);
return -1 means error
domain : AF_INET
protocol: 一般0
TCP: sockfd = socket(AF_INET, SOCK_STREAM, 0);
UDP: sockfd = socket(AF_INET, SOCK_DGRAM, 0);
绑定端口
int bind(int sockfd, struct sockaddr *sa, int addrlen);
连接网络(TCP)
int connect(int sockfd, struct sockaddr *servaddr, int addrlen);
监听端口(TCP)
int listen(int sockfd, int queue_length);
响应连接请求(TCP)
int accept(int sockfd, struct sockaddr *addr, int *addrlen);
关闭
int close(int sockfd);
int shutdown(int sockfd, int how);
0—-禁接收
1—禁发送
2—进收发
轮询
int select(int numfds, fd_set *readfds, fd_set * writefds, fd_set * exceptfds, struct timeval* timeout);
注意windows和unix中,函数返回后fd_set内容发生了改变,下次使用必须重新赋值。
接收和发送:
TCP: int send(int s, const void* buf, int len, int flags);
int recv(….);
UDP: int sendto(int s, const void* buf, int len, int flags, const struct sockaddr* to, int tolen);
int recvfrom(…);
基于消息的方式:
int sendmsg(int s, const struct msghdr * msg, int flags);
int recvmsg(…);