Want to know the ESSID of wireless network via C++ in UBUNTU

≡放荡痞女 提交于 2019-11-28 01:15:41

You should set length properly first before using werq, check this,

int sockfd;
    char * id;
   id = new char[IW_ESSID_MAX_SIZE+1];

    struct iwreq wreq;
    memset(&wreq, 0, sizeof(struct iwreq));
    wreq.u.essid.length = IW_ESSID_MAX_SIZE+1;

    sprintf(wreq.ifr_name, IW_INTERFACE);

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        fprintf(stderr, "Cannot open socket \n");
        fprintf(stderr, "errno = %d \n", errno);
        fprintf(stderr, "Error description is : %s\n",strerror(errno));
        exit(1);
    }
    printf("\nSocket opened successfully \n");

    wreq.u.essid.pointer = id;
    if (ioctl(sockfd,SIOCGIWESSID, &wreq) == -1) {
        fprintf(stderr, "Get ESSID ioctl failed \n");
        fprintf(stderr, "errno = %d \n", errno);
        fprintf(stderr, "Error description : %s\n",strerror(errno));
        exit(2);
    }

    printf("IOCTL Successfull\n");

    printf("ESSID is %s\n", (char *)wreq.u.essid.pointer);

You are testing the return code of ioctl(2) incorrectly. ioctl(2) returns -1 on error, not true (non-zero). Since an error is not being returned, the value in errno is undefined and is misleading.

It should read:

if (ioctl(sockfd,SIOCGIWESSID, &wreq) == -1) {
    fprintf(stderr, "Get ESSID ioctl failed \n");
    fprintf(stderr, "errno = %d \n", errno);
    fprintf(stderr, "Error description : %s\n",strerror(errno));
    exit(2);
}

Edit: With that incorrect code out of the way, there's this:

id = new char(IW_ESSID_MAX_SIZE+1);

Perhaps you meant:

id = new char[IW_ESSID_MAX_SIZE+1];

The former allocated only a single character and sets its value to IW_ESSID_MAX_SIZE+1. The latter allocates an array of size IW_ESSID_MAX_SIZE+1.

With that change, the code works for me and does not give an error for the ioctl.

Try setting wreq.u.essid.length to the right value.

ahmed koubaa

printf("Socket opened successfully \n");

//id = new char(IW_ESSID_MAX_SIZE+1);
char buffer[32];
memset(buffer, 0, 32);
wreq.u.essid.pointer = buffer;
wreq.u.essid.length = 32;

//wreq.u.essid.pointer = id;
if (ioctl(sockfd,SIOCGIWESSID, &wreq) == -1) {
    fprintf(stderr, "Get ESSID ioctl failed \n");
    fprintf(stderr, "errno = %d \n", errno);
    fprintf(stderr, "Error description : %s\n",strerror(errno));
    exit(2);
}
printf("IOCTL Successfull\n");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!