个人例子:void start_jrm(void)
{
FILE *fp;
char buf[4096];
unsigned int myport;
int on = 1;
int sockfd,new_fd,len;
SOCK_ATTR sock_attr;
struct sockaddr_in my_addr, their_addr;
char certificate[128] = "cacert.pem";
char privatekey[128] = "privkey.pem"; fp = fopen(config_file, "r");
while(fgets(buf, sizeof(buf), fp)){ if(strstr(buf,"listen_port")){
myport = atoi(buf+sizeof("listen_port"));
}
}
fclose(fp);
eric_print("bind port %d
",myport); //start_config_warden();
if ((sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_IP)) == -1) {
perror("socket");
exit(1);
} else
eric_print("socket created
"); bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = PF_INET;
my_addr.sin_port = htons(myport);//big or small endian problems my_addr.sin_addr.s_addr = 0;//why???? setsockopt (sockfd, SOL_SOCKET,SO_REUSEADDR,TCP_NODELAY, (void *) &on, sizeof (on)); //Solve the port takes up
if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
} else
eric_print("binded
"); if (listen(sockfd, 5) == -1) {
perror("listen");
exit(1);
} else{
eric_print("begin listen port %d
",myport);
}
sock_attr.ctx =init_ssl(0);
sec_load_cert_file(sock_attr.ctx,certificate,privatekey);//install certificate in server
while(1){
len = sizeof(struct sockaddr);
//in the listening state
if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr,&len)) == -1) {
perror("accept");
eric_print("accept error!
");
} else{
eric_print("tcp server: got connection from %s, port %d, socket %d
",
inet_ntoa(their_addr.sin_addr),
ntohs(their_addr.sin_port), new_fd);
}
sock_attr.sockfd = new_fd;
handle_connection(sock_attr);//to oprate the new sock every time, then continue listening ???
设置套接口的选项。#include #include int setsockopt(int sockfd, int level, int optname,const void *optval, socklen_t optlen);sockfd:标识一个套接口的描述字。level:选项定义的层次;支持SOL_SOCKET、IPPROTO_TCP、IPPROTO_IP和IPPROTO_IPV6。optname:需设置的选项。optval:指针,指向存放选项值的缓冲区。optlen:optval缓冲区长度。linux内核中定义为:static int setsockopt(struct socket *sock,int lvl, int opt, char __user *ov, unsigned int ol);setsockopt- set socketoption@sock: socketstructure@lvl: option level@opt: option identifie@ov: pointer to new option value@ol: length of option valueFor stream sockets only, accepts and ignores all IPPROTO_TCP options (to ease compatibility).Returns 0 on success, errno otherwise