rresvport.c 638 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /* posix */
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <time.h>
  8. /* socket extensions */
  9. #include <sys/socket.h>
  10. #include <netinet/in.h>
  11. #include <sys/un.h>
  12. int
  13. rresvport(int *p)
  14. {
  15. int fd;
  16. short i;
  17. struct sockaddr_in in;
  18. static int next;
  19. fd = socket(PF_INET, SOCK_STREAM, 0);
  20. if(fd < 0)
  21. return -1;
  22. i = 600 + ((getpid()+next++)%(1024-600));
  23. memset(&in, 0, sizeof(in));
  24. in.sin_family = AF_INET;
  25. in.sin_port = htons(i);
  26. printf("in.sin_port = %d\n", in.sin_port);
  27. if(bind(fd, &in, sizeof(in)) < 0){
  28. close(fd);
  29. return -1;
  30. }
  31. if(p)
  32. *p = i;
  33. return fd;
  34. }