connect()错误:不允许操作 [英] connect() error: operation not permitted

查看:194
本文介绍了connect()错误:不允许操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究UNIX网络编程中的示例,并且已经在此代码中将"daytimeclientcli.c"改编为特定于Linux的代码(这些示例使用BSD).我已经在此处上针对时间服务器运行了该程序.无论使用哪种服务器,我都会得到connect error: Operation not permitted,这是对connect()的调用的返回值.我到处搜寻,但是找不到与此相关的任何内容.任何帮助,我们将不胜感激.

I am working through examples in UNIX Network Programming and I've adapted "daytimeclientcli.c" into this code here which is linux specific (those examples use BSD). I've run the program against time servers on here. Regardless of the server i get connect error: Operation not permitted which is the return value from the call to connect(). I've searched around but I can't find anything related to this. Any help is greatly appreciated.

#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>

#define BUFFER 80
int main(int argc, char **argv) {
  int sockfd;
  int n;
  char buf[BUFFER+1];
  struct sockaddr_in servaddr;
  /* need a pointer to socketaddr for call to connect() */
  struct sockaddr* ptr;

  if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    fprintf(stderr, "socket error\n");
    return 2;
  }

  memset(&servaddr, 0, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(13);

  if (inet_pton(AF_INET, argv[1], &servaddr) <= 0) {
    fprintf(stderr, "inet_pton error for %s\n", argv[1]);
    return 3;
  }

  ptr = (struct sockaddr*) &servaddr;
  if (err = connect(sockfd, ptr, sizeof(servaddr)) < 0) {
    fprintf(stderr, "connect error: %s\n", strerror(err));
    return 4;
  }

  /* read from socket */
  while ( (n = read(sockfd, buf, BUFFER)) > 0);

  if (n < 0) {
    fprintf(stderr, "read error: %d\n", n);
    return 5;
  } else {
    /* null-terminate the buffer */
    buf[n] = 0;
    printf("%s\n", buf);
 }

  if (n < 0) {
    fprintf(stderr, "read error");
    return 5;
  }

  return 0;
}

推荐答案

connect()调用失败,因为servaddr尚未正确初始化.在对inet_pton()的调用中,尝试将& serv_addr"更改为& serv_addr.sin_addr".

The connect() call is failing because servaddr has not been initialized correctly. In the call to inet_pton(), try changing "&serv_addr" to "&serv_addr.sin_addr".

这篇关于connect()错误:不允许操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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