绑定错误(99):无法分配请求的地址 [英] Bind error (99): Cannot assign requested address

查看:162
本文介绍了绑定错误(99):无法分配请求的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使以下代码工作,但收到上述错误.我可以肯定地确定我输入的地址是正确的,因为它可以在执行类似任务的单独程序中使用.这使我相信我犯了一些愚蠢的错误,我们将不胜感激!

I am trying to get the following piece of code working but receiving the above error. I am reasonably sure that the address I am putting in is correct because it works in a separate program which is doing a similar task. This leads me to believe I am making some sort of silly mistake, any help would be appreciated!

   /*Create TCP socket*/
int tcp_socket(void)
{
    int s;
    while((s = socket(PF_INET,SOCK_STREAM,0))==-1 && errno == EINTR){
        continue;
    }
    return s;
}

/*Bind tcp*/
int tcp_bind(int s, char *server, uint16_t port)
{
    int             rv;
    struct sockaddr_in  sin;
    struct hostent      *host_addr;

    assert(s >= 0);

    host_addr = gethostbyname(server);
    if (!host_addr) {
        perror("gethostbyname(server)");
        return -1;
    }


    memset(&sin, '\0', sizeof sin);
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);

    sin.sin_addr = *((struct in_addr *)host_addr->h_addr);

    while((rv = bind(s,(struct sockaddr *)&sin, sizeof sin)) == -1
            && errno == EINTR) {
        continue;           
    }
    return (rv == 0) ? 0 : errno;
}

int connect_to_server()
{
    int rv;
    int socket = tcp_socket();
    _logf(LOG_DEBUG, "LOG %s:%d (%s) - %s:%d", __FILE__, __LINE__, __func__, "Socket created:", socket);

    rv = tcp_bind(socket,options.server_p, options.dest_port);
    if(rv != 0) {
        _logf(LOG_ALERT, "LOG %s:%d (%s) - %s:%s", __FILE__, __LINE__, __func__, "tcp_bind failed, error", strerror(rv));
        return -1;
    }
    else {
        _logf(LOG_ALERT, "LOG %s (%s) - %s:%d", __FILE__, __LINE__, __func__, "TCP bind success");  
    }
}

int main(int argc, char **argv)
{
    if (sysconf() == -1) {
        exit(-1);   
    }

    sysinit();

    if (parse_options(argc, argv) == -1) {
        usage();
        exit(1);
    }

    connect_to_server();
}

错误消息:

Sep 10 10:59:21 michael-VirtualBox mld: LOG mld.c:685 (connect_to_server) - tcp_bind failed, error:Cannot assign requested address

推荐答案

您只能将套接字绑定到本地接口的地址.

You can only bind a socket to an address of a local interface.

这篇关于绑定错误(99):无法分配请求的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆