- 论坛徽章:
- 3
|
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <errno.h>
- #include <string.h>
- int my_random_bind(int* pfd,unsigned short*pport)
- {
- static int x=0;
- int fd;
- unsigned short port,tmp;
- struct sockaddr_in addr;
- if(x == 0) {
- srand((unsigned)time(NULL));
- x = 1;
- }
- tmp=port=rand()%(0x10000-1024)+1024;
- while(port!=0xffff) {
- fd = socket(AF_INET, SOCK_DGRAM, 0);
- if(fd<0)
- return -1;
- memset(&addr,0,sizeof(addr));
- addr.sin_addr.s_addr = htonl(INADDR_ANY);
- addr.sin_family = AF_INET;
- addr.sin_port = htons(port);
- if(bind(fd,(struct sockaddr *)&addr, sizeof(struct sockaddr_in))<0) {
- if(errno == EADDRINUSE) {
- close(fd);
- port++;
- } else {
- close(fd);
- return -1;
- }
- } else {
- *pfd=fd;
- *pport=port;
- return 0;
- }
- }
- port=tmp-1;
- while(port!=1024) {
- fd = socket(AF_INET, SOCK_DGRAM, 0);
- if(fd<0)
- return -1;
- memset(&addr,0,sizeof(addr));
- addr.sin_addr.s_addr = htonl(INADDR_ANY);
- addr.sin_family = AF_INET;
- addr.sin_port = htons(port);
- if(bind(fd,(struct sockaddr *)&addr, sizeof(struct sockaddr_in))<0) {
- if(errno == EADDRINUSE) {
- close(fd);
- port--;
- } else {
- close(fd);
- return -1;
- }
- } else {
- *pfd=fd;
- *pport=port;
- return 0;
- }
- }
- return -2;
- }
复制代码 |
|