测试SO_REUSEADDR与绑定
示例代码1
//demo.cpp
#include <stdio.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <linux/tcp.h>
int SockDemo()
{
sockaddr_in in;
memset(&in,'\0',sizeof(in));
in.sin_family=AF_INET;
in.sin_port=htons(12345);
unsigned ip = 1234567;
//in.sin_addr.s_addr=INADDR_ANY;
in.sin_addr.s_addr=1234567;
int reuse0=1;
int serv=socket(AF_INET, SOCK_STREAM, 0);
if (setsockopt(serv, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse0, sizeof(reuse0))==-1)
{
return errno;
}
if (bind(serv, (sockaddr*)&in, sizeof(sockaddr)) == -1)
{
return errno;
}
//if (listen(serv, SOMAXCONN)==-1)
//{
// return errno;
//}
int reuse1=1;
int client=socket(AF_INET, SOCK_STREAM, 0);
if (setsockopt(client, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse1, sizeof(reuse1))==-1)
{
return errno;
}
//if (bind(client, (sockaddr*)&in, sizeof(sockaddr)) == -1)
//{
// return errno;
//}
//if (listen(serv, SOMAXCONN)==-1)
//{
// return errno;
//}
//sleep(10);
close(client);
close(serv);
return 0;
}
int main(int argc, char *argv[])
{
int errcode=SockDemo();
printf("errno=%d, %s.\n", errcode, strerror(errcode));
return 0;
}