-2

I'm following this tutorial https://www.geeksforgeeks.org/socket-programming-cc/. I'm trying to practice Socket Programming in C/C++. Can someone tell me why I'm recieving this error and how to fix it?

error C1083: Cannot open include file: 'unistd.h': No such file or directory

thanks in advance

#include<iostream>
#include<string>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080

using namespace std;

int main()
{

    int server_fd, new_socket, valread;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[1024] = { 0 };
    char *hello = "Hello from server";

    // Creating socket file descriptor
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
    {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // Forcefully attaching socket to the port 8080
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
        &opt, sizeof(opt)))
    {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // Forcefully attaching socket to the port 8080
    if (bind(server_fd, (struct sockaddr *)&address,
        sizeof(address))<0)
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    if (listen(server_fd, 3) < 0)
    {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
        (socklen_t*)&addrlen))<0)
    {
        perror("accept");
        exit(EXIT_FAILURE);
    }
    valread = read(new_socket, buffer, 1024);
    printf("%s\n", buffer);
    send(new_socket, hello, strlen(hello), 0);
    printf("Hello message sent\n");
    return 0;


return 0;
}
Svetlozar
  • 967
  • 2
  • 10
  • 23

1 Answers1

1

unistd.h is for a unix system. I assume you're working with windows?

emsimpson92
  • 1,779
  • 1
  • 9
  • 24
  • Yes, I'm with Windows. – Svetlozar Jun 05 '18 at 20:02
  • That would be your problem. You might want to see what exactly is being used in that library and find an alternative. – emsimpson92 Jun 05 '18 at 20:03
  • 1
    `#include ` as the first header file of your source files. – selbie Jun 05 '18 at 20:06
  • @selbie writing both with #include and #include ? – J.A Dec 12 '22 at 14:22
  • 1
    @J.A - you can `#ifdef WIN32` or `#ifdef linux` as appropriate and conditionally include windows and unix header files. That being said, there's usually a POSIX/Linux API that doesn't port directly to Windows as easily as including a header. – selbie Dec 12 '22 at 22:32