代码改变世界

一些demo

2019-09-07 16:27  Loull  阅读(180)  评论(0)    收藏  举报

 

 绑定端口demo:

#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <unistd.h>


int main() {
    int fd;
    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
            perror("cannot create socket");
                return 0;
    }

    int optval = 1;
    setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));

    struct sockaddr_in myaddr;

    /* bind to an arbitrary return address */
    /* because this is the client side, we don't care about the address */
    /* since no application will initiate communication here - it will */
    /* just send responses */
    /* INADDR_ANY is the IP address and 0 is the socket */
    /* htonl converts a long integer (e.g. address) to a network representation */
    /* htons converts a short integer (e.g. port) to a network representation */

    memset((char *)&myaddr, 0, sizeof(myaddr));
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(0);
    myaddr.sin_port = htons(53);

    if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
            perror("bind failed");
                return 0;
    }

    for(;;) {sleep(1000);}
}

 

rename demo:

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main () {
   int ret;
   char oldname[] = "/home/admin/logs/antdnsfilter/dnsfilter.log";
   char newname[] = "/home/admin/logs/antdnsfilter/dnsfilter.log.1";
   
   ret = rename(oldname, newname);
    
   if(ret == 0) {
      printf("File renamed successfully");
   } else {
      printf("Error: unable to rename the file.\n");
      printf("%d\n", ret);
      printf("errno:%d - %s\n", errno, strerror(errno));
   }
   
   return(0);
}