31
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

メカトロ講座03 c++でudp通信をする方法

Last updated at Posted at 2018-09-15

#概要
異なるコンピューター間で通信をしなければならない場合で簡単に通信がしたい場合は、UDPを使ってソケット通信するのがお手軽です。
以外とLinuxのC++でUDPのプログラムを書くのは情報が散逸していて、簡単な書き方がなかったのでまとめておきます(windowsだとincludeの名前などが少し変わってしまうはず)。
UDPはTCPと違って原理上は一方向の通信です。到達したかの応答もなく、送るほうはただ送るだけ受けるほうは受けるだけで、コネクションの確立などの操作もなく、簡単なシリアルポートと同じように使えます。

#ソース

共通部分

初期化やcloseの処理をしています。

simple_udp.h
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

class simple_udp{
	int sock;
	struct sockaddr_in addr;
public:
	simple_udp(std::string address, int port){
		sock = socket(AF_INET, SOCK_DGRAM, 0);
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = inet_addr(address.c_str());
		addr.sin_port = htons(port);		
	}
	void udp_send(std::string word){
		sendto(sock, word.c_str(), word.length(), 0, (struct sockaddr *)&addr, sizeof(addr));
	}
	
	void udp_bind(){
		bind(sock, (const struct sockaddr *)&addr, sizeof(addr));

	}
	std::string udp_recv(){
		#define BUFFER_MAX 400
		char buf[BUFFER_MAX];
		memset(buf, 0, sizeof(buf));
		recv(sock, buf, sizeof(buf), 0);
		return std::string(buf);
	}
	void udp_recv(char *buf, int size){
		memset(buf, 0, size);
		recv(sock, buf, size, 0);
	}
	
	~simple_udp(){
		close(sock);
	}
};

送信側

送信側は特に考えることはありません。相手のアドレスとポートを指定してクラスを作成して、送信メソッドを実行するだけです。
コネクションの確立などの操作は必要ありません。

send.c
#include <stdio.h>
#include "simple_udp.h"
simple_udp udp0("127.0.0.1",4001);

int main(int argc, char **argv){
  udp0.udp_send("hello!");
  return 0;
}

受信側

受信側ではアドレスは0.0.0.0を指定します(たしか、送信アドレスが何でも受け入れるという意味のはず)。ポートは送信側と合わせましょう。
受信前にudp_bind()を実行します。これで受信待ちの状態になります。udp_recv()で受信データを取得します。ここでブロッキングになることに注意

recv.c
#include <stdio.h>
#include <string.h>
#include "simple_udp.h"
simple_udp udp0("0.0.0.0",4001);

int main(int argc, char **argv){
  udp0.udp_bind();
  while (1){
	std::string rdata=udp0.udp_recv();
	printf("recv:%s\n", rdata.c_str());
  }
  return 0;
}

目次ページへのリンク

ROS講座の目次へのリンク

31
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?