首页 > 学院 > 开发设计 > 正文

ip和int互转的scala版本

2019-11-11 01:36:01
字体:
来源:转载
供稿:网友

ip和int互转的scala版本

有个群友问scala版本,刚好自己简单实现了个,发一下代码

代码:

import java.net.InetAddress/** * @author todd.chen at 16/01/2017 10:50. * email : todd.chen@ximalaya.com */object NetworkUtil { /** * get local ip with Int * * @return ip int */ def getLocalIp: Int = { val ip = InetAddress.getLocalHost.getHostAddress ip2Int(ip) } /** * ip transform to int * * @param ipAddress ip string * @return ip int */ def ip2Int(ipAddress: String): Int = { ipAddress.split("//.").zipWithIndex.foldLeft(0) { case (result, (ip, index)) ⇒ result | ip.toInt << (index * 8) } } /** * int transform to ip * * @param ip int ip * @return string ip */ def int2Ip(ip: Int): String = { s"${(0 to 3).map(i ⇒ (ip >> 8 * i) & 0xFF).mkString(".")}" }}

测试:

import org.scalatest.{FunSuite, Matchers}/** * @author todd.chen at 02/02/2017 11:23. * email : todd.chen@ximalaya.com */class NetworkUtilTest extends FunSuite with Matchers { test("testIp2Int") { val ip = NetworkUtil.ip2Int("192.168.120.60") ip should be(1014540480) } test("testInt2Ip") { val ip = 1014540480 val ipString = NetworkUtil.int2Ip(ip) ipString should be("192.168.120.60") } test("getLocalIp"){ val ip = NetworkUtil.getLocalIp val ipString = NetworkUtil.int2Ip(ip) val ipInt = NetworkUtil.ip2Int(ipString) ip should equal(ipInt) }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表