Question

Is there a way to send a message to a remote syslog in c++ code?

equivalent to this line in linux command:

nc -w0 -u 192.168.1.1 514 <<< "logging from remote"

This code supposed to do the some thing with socket but it doesn't work.

int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0,n;
struct sockaddr_in serv_addr;
    struct hostent *server;


char sendBuff[1025];
sprintf(sendBuff,"bla bla");

time_t ticks; 

listenfd = socket(AF_INET, SOCK_DGRAM , 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff)); 

serv_addr.sin_family = AF_INET;
server = gethostbyname("192.168.1.108");
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);

//serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(514); 

    if ((n=connect(connfd,(const sockaddr*)&serv_addr,sizeof(serv_addr))) < 0){
            printf(" Connection to has failed Server ");
    }


bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); 

listen(listenfd, 10); 

while(1)
{
    connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); 

    write(connfd, sendBuff, strlen(sendBuff)); 

    close(connfd);
    sleep(60);
}

}

Was it helpful?

Solution 2

nc -u just sends data over UDP sockets. There's nothing particular about it, no specific protocol to follow: it's just raw data. You can simply send your messages through UDP sockets in C++ (see socket with AF_INET, SOCK_DGRAM parameters and other related functions).

But this means you miss a lot of syslog's features like facilities and priorities.

@Moose is right: the syslog API is more relevant to your needs, since it is much more flexible (no need to modify your program if you want to change the behaviour, you'll only have to reconfigure the syslog daemon).

OTHER TIPS

On several Unixes, including Linux you may simply use the client command http://linux.die.net/man/3/syslog and install a current syslog server such as syslog-ng. This server will be able to not only filter the messages according to your rules but also send them to any remote syslog.

If you are on Windows, I'm afraid you have to implement your own syslog protocol. Luckily, it's not that difficult and more or less defined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top