Unix socket 编程API二之辅助函数

一:网络字节序跟主机字节序转换:

#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong); //host to network long
uint16_t htons(uint16_t hostshort);//host to network short
uint32_t ntohl(uint32_t netlong);  //network to host long
uint16_t ntohs(uint16_t netshort); //network to host short

eg:查看主机是大端字节序还是小端字节序
 

#include	"unp.h"

int main(int argc, char **argv)
{
	union {
	  short  s;
      char   c[sizeof(short)];
    } un;

	un.s = 0x0102;
	printf("%s: ", CPU_VENDOR_OS);
	if (sizeof(short) == 2) {
		if (un.c[0] == 1 && un.c[1] == 2)
			printf("big-endian\n");
		else if (un.c[0] == 2 && un.c[1] == 1)
			printf("little-endian\n");
		else
			printf("unknown\n");
	} else
		printf("sizeof(short) = %d\n", sizeof(short));

	exit(0);
}

二:地址转换函数
 

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int inet_aton(const char *cp, struct in_addr *inp); //将字符串地址cp转为struct in_addr结构
in_addr_t inet_addr(const char *cp);//将字符串地址cp转为in_addr_t结构
in_addr_t inet_network(const char *cp);//将字符串地址cp转为in_addr_t结构
char *inet_ntoa(struct in_addr in);//将struct in_addr地址结构转换为字符串
#include <arpa/inet.h>
       
int inet_pton(int af, const char *src, void *dst);
const char *inet_ntop(int af, const void *src,char *dst, socklen_t size);

三:获取一个连接的本地地址/对端地址
 

#include <sys/socket.h> 
int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

四:select

/* According to earlier standards */
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int select(int nfds, fd_set *readfds, fd_set *writefds,
           fd_set *exceptfds, struct timeval *timeout);

void   FD_CLR(int fd, fd_set *set);
int  FD_ISSET(int fd, fd_set *set);
void   FD_SET(int fd, fd_set *set);
void   FD_ZERO(fd_set *set);

#include <sys/select.h>

int pselect(int nfds, fd_set *readfds, fd_set *writefds,
            fd_set *exceptfds, const struct timespec *timeout,
            const sigset_t *sigmask);

五:套接字选项
 

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>

int getsockopt(int sockfd, int level, int optname,void *optval, socklen_t *optlen);
int setsockopt(int sockfd, int level, int optname,const void *optval, socklen_t optlen);

 

 

 

 

 

展开阅读全文

没有更多推荐了,返回首页