实现readline,gethostname,gethostbyname

来源:互联网 发布:藤门留学收费 知乎 编辑:程序博客网 时间:2024/05/29 09:12

recv可以通过flag选项指定行为。。例如msg_peek可以接受缓冲区数据,但不从缓冲区中清除。。这就是他跟read函数的区别,read函数把数据从缓冲区中读走,缓冲区的数据就被清除。。

readline也可以解决粘包问题,比如说ftp就是这样的,\r\n

vim中===老忘

1.删除当前行后面所有的行:

,$d

2.删除第一行到当前行:

1,.d

======

readline的核心就是用一个偷看函数MSG_PEEK

getsockname,getpeername..

gethostname,gethostbyname,gethostbyaddr..

代码:

/*
 * socket03_echocli.cpp
 *
 *  Created on: Oct 15, 2016
 *      Author: root
 */




#include <arpa/inet.h>
#include <asm-generic/errno-base.h>
#include <errno.h>
#include <netinet/in.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <netdb.h>

using namespace std;
#define ERR_EXIT(m) printf("error")

int getlocalip(char *ip){
    char host[100] = {0};
    if(gethostname(host, sizeof(host)) < 0) return -1;
    struct hostent *hp;
    if((hp = gethostbyname(host)) == NULL) return -1;
    strcpy(ip, inet_ntoa(*(struct in_addr*)hp->h_addr_list[0]));
    return 0;
}

int main(void){
    char host[100] = {0};
    if(gethostname(host, sizeof(host)) < 0)
        ERR_EXIT("gethostname");
    struct hostent *hp;
    if((hp = gethostbyname(host)) == NULL)
        ERR_EXIT("gethostbyname");
    int i=0;

    while(hp->h_addr_list[i] != NULL)
    {
        printf("%s\n",innet_ntoa(*(struct in_addr*)hp->h_addr_list[i]));
        i++;
    }
    char ip[16] = {0};
    getlocal(ip);
    printf("localip=%s\n", ip);

    return 0;


}


0 0